简体   繁体   English

PHP 和带有小数的单元测试断言

[英]PHP and unit testing assertions with decimals

I have a method that returns a float like 1.234567890.I want to test that it really does so.我有一个方法可以返回像 1.234567890 这样的浮点数。我想测试它是否真的这样做了。 However, it seems that this returned float has different precision on different platforms so how do I assert that the returned value is 1.23456789?但是,这个返回的浮点数似乎在不同平台上具有不同的精度,所以我如何断言返回的值为 1.23456789? If I just do:如果我只是这样做:

$this->assertEqual(1.23456789, $float);

Then that might fail on some platforms where there is not enough precision.然后在某些精度不够的平台上可能会失败。

So far it hasn't been mentioned that assertEquals supports comparing floats by offering a delta to specifiy precision :到目前为止,还没有提到 assertEquals 通过提供 delta 来支持比较浮点数来指定精度

$this->assertEquals(1.23456789, $float, '', 0.0001);

Thanks to @Antoine87 for pointing out : since phpunit 7.5 you should use assertEqualsWithDelta() :感谢@Antoine87指出从 phpunit 7.5 开始,您应该使用assertEqualsWithDelta()

$this->assertEqualsWithDelta(1.23456789, $float, 0.0001);

作为对@bernhard-wagner 答案的更新,您现在应该使用assertEqualsWithDelta() 自 phpunit 7.5

$this->assertEqualsWithDelta(1.23456789, $float, 0.0001);

In general, it's a bad idea to test built-in floats for equality.一般来说,测试内置浮点数是否相等是个坏主意。 Because of accuracy problems of floating point representation, the results of two different calculations may be perfectly equal mathematically, but different when you compare them at your PHP runtime.由于浮点表示的 准确性问题,两个不同计算的结果在数学上可能完全相等,但在 PHP 运行时比较它们时会有所不同。

Solution 1: compare how far apart they are.解决方案1:比较它们相距多远。 Say, if the absolute difference is less than 0.000001, you treat the values as equal.比如说,如果绝对差小于 0.000001,则您将这些值视为相等。

Solution 2: use arbitrary precision mathematics , which supports numbers of any size and precision, represented as strings.解决方案2:使用任意精度数学,它支持任意大小和精度的数字,表示为字符串。

为了获得更高的准确性,您可以考虑使用BCMath

或者使用 bcmath() 您还可以设置默认精度,如下所示:

ini_set('precision', 14);

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

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