简体   繁体   English

如何使用 pytest 对小数位数进行近似计算?

[英]How to approx values on decimal places using pytest?

Looking through the documentation it says that by default the approx method evaluate until 3 decimal places on a number, but when i compare this value it returns False查看 文档,它说默认情况下, approx方法计算一个数字直到小数点后 3 位,但是当我比较这个值时它返回False

pytest.approx(6.495) == 6.49  # False

How can i check if a number is approx.我如何检查一个数字是否约为。 to another within decimal places?到小数点内的另一个?

It doesn't say that the default is within three decimal places, it says it's within 1e-6 - or 0.000001 .它并不是说默认值在小数点后三位以内,而是说在1e-6 - 或0.000001以内。

By default, approx considers numbers within a relative tolerance of 1e-6 (ie one part in a million) of its expected value to be equal.默认情况下,approx 认为在其预期值的 1e-6(即百万分之一)的相对容差范围内的数字是相等的。 This treatment would lead to surprising results if the expected value was 0.0, because nothing but 0.0 itself is relatively close to 0.0.如果期望值为 0.0,这种处理将导致令人惊讶的结果,因为只有 0.0 本身相对接近 0.0。 To handle this case less surprisingly, approx also considers numbers within an absolute tolerance of 1e-12 of its expected value to be equal.为了不那么令人惊讶地处理这种情况, approx 还认为其期望值的绝对容差为 1e-12 内的数字是相等的。

The rel argument can be used to change what's consider approximately the same value: rel参数可用于更改认为大致相同的值:

>>> pytest.approx(6.495, rel=1e-3) == 6.49
True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM