Odd behavior comparing doubles, two PHP double values aren#39;t equivalent(比较双精度的奇怪行为,两个 PHP 双精度值不等价)
问题描述
我在 PHP 中有两个看似相等的 double 值(至少在回显它们时).
I have two seemingly equal double values in PHP (at least when echoing them).
但是当将它们与双等号进行比较时,由于某种原因,它的评估结果为假.进行此类比较时是否有任何特殊注意事项?
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?
推荐答案
您不应该使用 ==
运算符比较浮点数.
You shouldn't compare floating point numbers using the ==
operator.
查看大警告和php 手册中的解释
有效的方法是断言这两个数字彼此之间存在一定的小距离,如下所示:
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 双精度值不等价的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:比较双精度的奇怪行为,两个 PHP 双精度值不等价


基础教程推荐
- 超薄框架REST服务两次获得输出 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 在多维数组中查找最大值 2021-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01