为什么0.1 + 0.2-0.3 = 5.5511151231258E-17在PHP中 [英] why 0.1+0.2-0.3= 5.5511151231258E-17 in php

查看:957
本文介绍了为什么0.1 + 0.2-0.3 = 5.5511151231258E-17在PHP中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

PHP float的精确计算


当我在eclipse中执行下面的代码,结果不是0,而是5.5511151231258E-17

  $ a = 0.1 + 0.2-0.3; 
echo $ a;

有人可以告诉我为什么吗?

解决方案

这是因为浮点数的精度有限

你可以在上找到更多关于这个特质的信息。这个页面在PHP手册中。


浮点数的精确度有限。尽管它依赖于系统的
,但PHP通常使用IEEE 754双精度格式
,由于$ 1.11e-16的顺序
的四舍五入,会产生最大的相对误差。非基本的算术运算可能给出更大的
错误,当然,当
几个操作被复合时,必须考虑错误编程。

另外,有理数可以用10进制表示为
的浮点数,比如0.1或者0.7,在基数2中没有
的精确表达式作为浮点数,也就是
在内部使用,不管尾数的大小。因此,他们
不能被转换成他们的内部二进制副本,没有
小的精度损失。这可能会导致混乱的结果:例如,对于
,floor((0.1 + 0.7)* 10)通常会返回7而不是
expected 8,因为内部表示将类似
7.9999999999999991118 ....

因此,不要将浮点数结果相信到最后一位数字,也不要将
比较浮点数是否相等。如果更高的精度是
必要的,任意的精确数学函数和gmp函数
都可用。

请注意这不是PHP特有的特征; 这只是浮点数的工作方式


Possible Duplicate:
The accuracy of PHP float calculate

when i executed the code below in eclipse , the result was not 0 but 5.5511151231258E-17

$a = 0.1+0.2-0.3;
echo $a;

could someone tell me why?

解决方案

This is because floating point numbers have limited precision.

You can find more information about this trait on this page in the PHP manual.

Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error progragation must be considered when several operations are compounded.

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118....

So never trust floating number results to the last digit, and never compare floating point numbers for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

Please note that this is not a trait specific to PHP; it is just the way floating point numbers work.

这篇关于为什么0.1 + 0.2-0.3 = 5.5511151231258E-17在PHP中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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