Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can 12.1 be represented exactly as a floating point number?

This is in reference to the comments in this question:

This code in Java produces 12.100000000000001 and this is using 64-bit doubles which can present 12.1 exactly. – Pyrolistical

Is this true? I felt that since a floating point number is represented as a sum of powers of two, you cannot represent 12.1 exactly, no matter how many bits you have. However, when I implemented both the algorithms and printed the results of calling them with (12.1, 3) with many significant digits, I get, for his and mine respectively:

12.10000000000000000000000000000000000000000000000000000000000000000000000000 12.10000000000000100000000000000000000000000000000000000000000000000000000000

I printed this using String.format("%76f"). I know that's more zeros than necessary, but I don't see any rounding in the 12.1 .

like image 848
Claudiu Avatar asked Nov 27 '22 21:11

Claudiu


2 Answers

No. As others noted in followups to his comment, no sum of (a finite number of) powers of two can ever add up to exactly 12.1. Just like you can't represent 1/3 exactly in base ten, no matter how many digits you use after the decimal point.

like image 167
Aric TenEyck Avatar answered May 26 '23 15:05

Aric TenEyck


In binary, 12.1 is:

1100.000110011001100110011...

Since this doesn't terminate, it can't be represented exactly in the 53 significand bits of a double, or any other finite-width binary floating-point type.

like image 39
Stephen Canon Avatar answered May 26 '23 16:05

Stephen Canon