ruby - MiniTest 的 assert_in_delta 和 assert_in_epsilon 方法有什么区别?

标签 ruby minitest approximate

这里是 documentation for assert_in_delta :

assert_in_delta(exp, act, delta = 0.001, msg = nil) public

For comparing Floats. Fails unless exp and act are within delta of each other.

assert_in_delta Math::PI, (22.0 / 7.0), 0.01

这里是 documentation for assert_in_epsilon

assert_in_epsilon(a, b, epsilon = 0.001, msg = nil) public

For comparing Floats. Fails unless exp and act have a relative error less than epsilon.

这些看起来很相似;到底有什么区别?您什么时候会使用一种方法而不是另一种方法?

最佳答案

主要区别在于:

  • assert_in_delta 用于绝对错误。
  • assert_in_epsilon 用于相对错误。

这是两种不同类型的 approximation error :

The absolute error is the magnitude of the difference between the exact value and the approximation.

The relative error is the absolute error divided by the magnitude of the exact value.


assert_in_delta 最容易理解,最常用于测试。

在文档的示例中:assert_in_delta Math::PI, (22.0/7.0), 0.01,此断言将通过,因为 22.0/7 - Math: :PI == 0.001264...,小于 0.01 的允许 delta


(来自wikipedia)

assert_in_epsilon 通常用于比较大小差异很大的数字的近似值。

例如,在大多数应用程序中,以 3 的绝对误差逼近数字 1,000 比逼近数字 1,000,000 差得多绝对误差为 3;在第一种情况下,相对误差为 0.003,而在第二种情况下,它仅为 0.000003

要在 MiniTest 中编写此示例,假设我们有一个包含两个值的数组,我们要检查这两个值“大约等于”1,0001,000,000分别。我们可以这样写:

# Using the default `epsilon` of 0.001
assert_in_epsilon(1_000, actual[0])
assert_in_epsilon(1_000_000, actual[1])

这在功能上等同于写作:

assert_in_delta(1_000, actual[0], 1)
assert_in_delta(1_000_000, actual[1], 1000)

关于ruby - MiniTest 的 assert_in_delta 和 assert_in_epsilon 方法有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39743448/

相关文章:

ruby - 如何使用 minitest 测试实例级 Sequel::Model 验证

python - 近似匹配的位置

ruby-on-rails - 在 Rails 中向现有模型添加验证

ruby - Ruby 中的反射。通过给定的类名实例化一个对象

ruby - Minitest 中 RSpecs instance_double 的对应物是什么?

ruby-on-rails - Minitest 控制台输出不显示颜色

r - 尝试使用近似函数找到交点,结果在 y 轴上正确,但在 x 轴上偏离

java - 如何查看一个对象是否更近似相等

ruby-on-rails - Rails 4.2 应用程序开发速度非常慢

ruby-on-rails - 在 Rails 上使用 Ruby 1.9 是否可行?