为什么PHP将(int)((0.1 + 0.7)* 10)的结果转换为7而不是8? [英] Why would on earth PHP convert the result of (int) ((0.1+0.7)*10) to 7, not 8?

查看:429
本文介绍了为什么PHP将(int)((0.1 + 0.7)* 10)的结果转换为7而不是8?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么PHP将(int)((0.1 + 0.7)* 10)的结果转换为7而不是8?我知道当它被转换为(int)时,结果是(float)8 ,结果是7?为什么会发生这种情况?

解决方案

这些都是关于 float 的。请参阅 PHP:浮点数


警告 - 浮点精度

浮点数精度有限。虽然它取决于系统,但是PHP通常使用IEEE 754双精度格式,由于按照1.11e-16的顺序舍入,所以会产生最大的相对误差。非基本的算术运算可能会给出更大的错误,当然,当多个运算复合时,错误传播必须被考虑。

另外,有理数可以精确地表示为浮点在基数为10的点号(如0.1或0.7)中没有精确的表示形式作为基数为2的浮点数,在内部使用,无论尾数的大小。因此,他们不能被转换成他们的内部二进制对应,没有一点精确度的损失。这可能导致令人困惑的结果:例如,floor((0.1 + 0.7)* 10)通常会返回7而不是预期的8,因为内部表示将类似于7.9999999999999991118 .... 因此,不要将浮点数结果信任到最后一位,也不要直接比较浮点数是否相等。如果需要更高的精度,可以使用任意的精度数学函数和gmp函数。

附加阅读:

'UL>

  • 每位计算机科学家应该知道什么是浮点运算 有多危险它比较浮点值?

  • 为什么不能显示十进制数完全是二进制?


  • Why would on earth PHP convert the result of (int) ((0.1+0.7)*10) to 7, not 8? I know that the result will be (float) 8 when it's cast to (int) the result will be 7? Why does that happen?

    解决方案

    It is all about float. See PHP: Floating point numbers:

    Warning - Floating point precision

    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 propagation 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 do not compare floating point numbers directly for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

    Additional reading:

    这篇关于为什么PHP将(int)((0.1 + 0.7)* 10)的结果转换为7而不是8?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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