gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:06:02 24 4
gpt4 key购买 nike

这里是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com