问题
Okay so I get that some numbers can't be represented properly in binary just like 1/3 can't be fully represented in decimal.
So how come when I console.log(0.3) it returns 0.3 but when I console.log(0.1 + 0.2) it returns the 0.30000000000000004
How come it is accounting for the error (if it even is) when simply outputting 0.3 but doesn't when the addition occurs?
回答1:
Suppose we approximate 1/3 and 2/3 in decimal.
1/3 = 0.333
2/3 = 0.667
and we add 1/3+1/3:
1/3+1/3 = 0.333 + 0.333 = 0.666
We didn't get our approximation of 2/3. Rounding 1/3 to something we can represent in decimal didn't produce a number equal to half of what we got when we rounded 2/3.
The same thing happens in binary. We round 0.1 and 0.2 to numbers we can represent in binary, but the sum of the approximations is slightly different from what we get if we approximate 0.3. We get something a bit higher, and the result is displayed as 0.30000000000000004
.
回答2:
The inaccuracies in the internal representations of 0.1
and 0.2
are small enough that the Javascript printer ignores them when it's printing these numbers. But when you add them together the inaccuracies accumulate, and this is enough to show up when the result is printed.
回答3:
The way Java prints floating-point numbers is a significant part of the behavior you are seeing: By default, Java does not print the exact value of a floating-point number. It prints just enough digits to precisely identify the double
that is being printed.
Thus, if you set x
to .3
, x
is actually set to 0.299999999999999988897769753748434595763683319091796875. When Java prints this, it prints only “.3”, because converting “.3” to double
yields the value of x
, 0.299999999999999988897769753748434595763683319091796875.
When you use .1
and .2
, these are actually the values 0.1000000000000000055511151231257827021181583404541015625 and 0.200000000000000011102230246251565404236316680908203125. When you add them (in double
format), the result is 0.3000000000000000444089209850062616169452667236328125.
When you print this value, Java prints “0.30000000000000004” because it needs to show all those digits in order to produce a numeral that, when converted back to double
, will produce 0.3000000000000000444089209850062616169452667236328125.
Here is the documentation for how double values are printed. It says:
How many digits must be printed for the fractional part…? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type
double
.
回答4:
As you said, in base 10 you can't accurately describe the fraction 1/3. Similarly, in base 2, you can't accurately describe certain other fractions. So, when the computer adds 0.1 and 0.2, it's actually adding something like 0.10000000001 and 0.20000000003.
来源:https://stackoverflow.com/questions/21490511/general-floating-point-maths-query