比较双打的奇怪行为,两个PHP double值不相等 [英] Odd behavior comparing doubles, two PHP double values aren't equivalent

查看:85
本文介绍了比较双打的奇怪行为,两个PHP double值不相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在PHP中有两个看似相等的double值(至少在回显它们时)。

I have two seemingly equal double values in PHP (at least when echoing them).

但是将它们与double equals进行比较时,由于某种原因,它的计算结果为false。在执行这种比较时,有什么特殊的考虑吗?

But when comparing them with double equals, for some reason, it evaluates to false. Are there any special considerations when performing this kind of comparison?

推荐答案

您不应使用<$ c比较浮点数$ c> == 运算符。

请参阅大警告和 php手册中的说明

See the big warning and explanation in the php manual

将要起作用的是断言这两个数字彼此之间相距一定距离,例如:

What will work is asserting that the two numbers are within a certain small distance of each other like this:

if(abs($a - $b) < 0.0001) {
    print("a is mostly equal to b");
}

原因是由于小数点后执行浮点运算而导致舍入错误转换为二进制,然后转换回十进制。这些来回转换会导致 0.1 + 0.2 不等于 0.3 的现象。

The reason is because of rounding errors due to floating point arithmetic performed after the decimals are converted to binary, then converted back to decimal. These back and forth conversions cause the phenomenon where 0.1 + 0.2 does not equal 0.3.

这篇关于比较双打的奇怪行为,两个PHP double值不相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆