Sum of 3 variables: strange behavior
Possible Duplicate:
Is JavaScript's Math broken?
Why can't decimal numbers be represented exactly in binary?
What will be result of next code:
if(0.3 == ( 0.1 + 0.1 + 0.1 ))
{
alert(true);
}
else
{
alert(false);
}
It is strange, but result will be false.
Reason is that result of
0.1+0.1+0.1
will be
0.30000000000000004
How can be explained this behavior?
解释很简单 - 阅读浮点数问题
It's the same reason 1/3 + 1/3 + 1/3 may not give you exactly 1 in decimal. If you use 1/3 as .33333333, then 1/3 + 1/3 + 1/3
will give you .9999999
which isn't exactly one.
Unless you know exactly what you're doing, don't compare non-integer numeric types for equality.
What you're experiencing is a basic floating point rounding error.
We can't precisely represent 0.1 without some error due to the nature of binary numbers. WolframAlpha reports decimal 0.1 to equal binary ~0.00011001100110011... Notice how it can't be finitely represented in the binary number system? This means we have to decide on a cut off point at which to stop calculating this number otherwise we'd be here forever.
This introduces an error. And this error has accumulated as the code adds the numbers together which results in an incredibly small quantity added to the end of your sum. This ensures that the sum will never be EXACTLY 0.3, which is what the IF
test is looking for.
Some decimal numbers, however, can be represented accurately in binary such as dec 0.5 = bin 0.1 and dec 0.25 = bin 0.01.
We can demonstrate this similarly to your original code by using 0.5 = (0.25 + 0.25).
For further reading on this I recommend The Floating-Point Guide .
It provides a good overview of the concept of floating point numbers and how errors in calculation can arise. There is also a section on Javascript which demonstrates how to overcome the rounding errors you're experiencing.
链接地址: http://www.djcxy.com/p/27498.html上一篇: c#和javascript中的IEEE 754浮点运算舍入错误
下一篇: 3个变量之和:奇怪的行为