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

发布于 2024-08-16 13:49:58 字数 204 浏览 1 评论 0原文

我有一个返回像 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

羁〃客ぐ 2024-08-23 13:49:59

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

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

As an update to @bernhard-wagner answer, you should now use assertEqualsWithDelta() since phpunit 7.5.

$this->assertEqualsWithDelta(1.23456789, $float, 0.0001);
总以为 2024-08-23 13:49:59

一般来说,测试内置浮点数的相等性不是一个好主意。由于浮点表示的精度问题,两种不同计算的结果可能是完美的在数学上是相等的,但是当您在 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.

樱娆 2024-08-23 13:49:59

除了使用 bcmath() 之外,您还可以设置默认精度,如下所示:

ini_set('precision', 14);

Alternatively of using bcmath() you can also set the default precision, like this:

ini_set('precision', 14);
羅雙樹 2024-08-23 13:49:58

到目前为止,还没有提到assertEquals支持通过 提供增量来指定精度

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

感谢@Antoine87 指出:从 phpunit 7.5 开始,你应该使用assertEqualsWithDelta():

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

So far it hasn't been mentioned that assertEquals supports comparing floats by offering a delta to specifiy precision:

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

Thanks to @Antoine87 for pointing out: since phpunit 7.5 you should use assertEqualsWithDelta():

$this->assertEqualsWithDelta(1.23456789, $float, 0.0001);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文