PHP 和带小数的单元测试断言
我有一个返回像 1.234567890 这样的浮点数的方法。我想测试它是否确实如此。但是,似乎这个返回的浮点数在不同的平台上具有不同的精度,那么我如何断言返回的值为1.23456789?如果我这样做:
$this->assertEqual(1.23456789, $float);
那么在某些精度不够的平台上可能会失败。
I have a method that returns a float like 1.234567890.I want to test that it really does so. 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? If I just do:
$this->assertEqual(1.23456789, $float);
Then that might fail on some platforms where there is not enough precision.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
作为 @bernhard-wagner 答案的更新,您现在应该使用
assertEqualsWithDelta()
自 phpunit 7.5 起。As an update to @bernhard-wagner answer, you should now use
assertEqualsWithDelta()
since phpunit 7.5.一般来说,测试内置浮点数的相等性不是一个好主意。由于浮点表示的精度问题,两种不同计算的结果可能是完美的在数学上是相等的,但是当您在 PHP 运行时比较它们时,它们是不同的。
解决方案1:比较它们之间的距离。假设,如果绝对差值小于 0.000001,则将这些值视为相等。
解决方案2:使用任意精度数学,它支持任意大小的数字和精度,表示为字符串。
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.
Solution 1: compare how far apart they are. Say, if the absolute difference is less than 0.000001, you treat the values as equal.
Solution 2: use arbitrary precision mathematics, which supports numbers of any size and precision, represented as strings.
除了使用 bcmath() 之外,您还可以设置默认精度,如下所示:
Alternatively of using bcmath() you can also set the default precision, like this:
到目前为止,还没有提到assertEquals支持通过 提供增量来指定精度:
感谢@Antoine87 指出:从 phpunit 7.5 开始,你应该使用assertEqualsWithDelta():
So far it hasn't been mentioned that assertEquals supports comparing floats by offering a delta to specifiy precision:
Thanks to @Antoine87 for pointing out: since phpunit 7.5 you should use
assertEqualsWithDelta()
: