Java language is inaccurate for calculations? -
this question has answer here:
- is floating point math broken? 20 answers
- java float unexpectedly rounded 3 answers
i tried following for
loop:
for(double = 0.0; i<=0.001; i+=0.0001) system.out.println(i);
and following output:
0.0
1.0e-4
2.0e-4
3.0000000000000003e-4
4.0e-4
5.0e-4
6.000000000000001e-4
7.000000000000001e-4
8.000000000000001e-4
9.000000000000002e-4
my questions are:
- how these
.000000000000001
s come? - will these numbers come, or there problem in code?
- do these errors occur in java language, or other programming languages too?
- is
double
suitablefor
loops?
sadly, not numbers can represented in floating point:
for example, decimal number 0.1 not representable in binary floating-point of finite precision; exact binary representation have "1100" sequence continuing endlessly:
e = −4; s = 1100110011001100110011001100110011..., where, previously, s significand , e exponent.
when rounded 24 bits becomes
e = −4; s = 110011001100110011001101, 0.100000001490116119384765625 in decimal.
Comments
Post a Comment