简体   繁体   English

PHP用负数计算得出错误的值

[英]PHP calculating with negative numbers gives wrong values

My PHP code: 我的PHP代码:

echo -100.35+100.00;
echo '<br/>';
echo -478.35+478.32+0.03;

Gives output: 给出输出:

-0.34999999999999
-2.9559688030645E-14

I don't understand why, i tried (float) in front of the values but no difference. 我不明白为什么,我在值之前尝试过(浮动)但没有区别。

您应使用BC数学函数进行此类计算。

Take a look at this manual , it explains that the internal representation is not 100% exact for floats... it has to do with the internal representation of the floats I suspect. 看一下本手册 ,它解释了浮子的内部表示不是100%精确的...它与我怀疑的浮子的内部表示有关。

The manual does also refer to these methods and also these for calculations with need of precision. 手动的确也指这些方法 ,也这些与需要的精度计算。

This is how floats work. 浮动就是这样工作的。 In PHP, there are integers, or there are floats - no exact decimals or the like. 在PHP中,有整数,也有浮点数-没有精确的小数点或类似内容。

Floats are simply not EXACT - there isn't too much you can do about it. 浮点数根本不是精确的-您对此无能为力。 http://www.php.net/manual/en/language.types.float.php http://www.php.net/manual/en/language.types.float.php

Note the big warning: 注意大警告:

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. 尽管它取决于系统,但PHP通常使用IEEE 754双精度格式,由于舍入为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. 此外,在底数10中可精确表示为浮点数的有理数(如0.1或0.7)在底数2中没有作为浮点数的精确表示,内部使用,而不考虑尾数的大小。 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.... 这可能导致混乱的结果:例如,floor((0.1 + 0.7)* 10)通常返回7而不是预期的8,因为内部表示形式类似于7.9999999999999991118 ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM