I have this code sample:
float approx = 1234567712f;
System.out.println(approx);
Instead of printing "1.234567712E9" or something similar it prints "1.23456768E9". As I understand, this has something to do with precision at the binary level.
How many binary digits is the precision for float numbers (before and after the comma (",") symbol)? Can you explain it in a simple way why is this happening?
-
en.wikipedia.org/wiki/Single-precision_floating-point_formatrgettman– rgettman2013年11月22日 19:26:26 +00:00Commented Nov 22, 2013 at 19:26
-
1This question has been asked 100's of times in different forms. It always comes back to the fact that the "significand" of a 32 bit floating point number only has 23 bits in it. You cannot express a number to greater accuracy than one part in 2^24. Thus in floating point, 2^24 + 1 == 2^24. And 2^24 ~ 16M. See What every computer scientist should know about floating pointFloris– Floris2013年11月22日 19:33:03 +00:00Commented Nov 22, 2013 at 19:33
2 Answers 2
A floating point number consists of a "significand" and an "exponent". To represent integers down to the last odd digit, the exponent would have to be zero. This means that you have 24 bits available (the 24th bit is always 1 and therefore not stored), and the largest integer you can store is
0xFFFFFF == 16777215
When you want to add 2 to this number, the "accurate" representation would be
0x1000001 =わ 16777217
You would need 25 bits to store this number; so the last digit gets lopped off, and the number will be stored as
0x800000 x 2^1 == 16777216
As numbers get larger, the "jump" between successive representable numbers gets bigger. By the time you get to
1234567112 == 0x4995FFC8
You would need 32 bits to store it. But you only have 24 bits, so it will be stored internally as something like
0x499600 x 2^8 (rounded to the closest number).
= 0x49960000 =わ 1234567168
which is the number you saw.
Comments
float has a precision up to 7 digits before and after the comma. That's why 1234567 is correct and the other 3 digits aren't. You should use double instead of float if you want to calculate with high numbers
Comments
Explore related questions
See similar questions with these tags.