Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is arbitrary precision in double literals allowed in Java?

I just learned from Peter Lawreys post that this is valid expression, and evaluates to true.

333333333333333.33d == 333333333333333.3d

My question is, why is it allowed to have double literals which can't be represented in a double, while integer literals that can't be represented are disallowed. What is the rationale for this decision.


A side note, I can actually trigger out of range compile error for doubles literals :-)

99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999d

So as long as we're in (min, max) range, the literal gets approximated, but when going outside of that, it seems the compiler refuses to approximate it.

like image 740
aioobe Avatar asked Aug 16 '11 10:08

aioobe


People also ask

What is the precision of double data type in Java?

The double data type is a 64-bit double-precision IEEE 754 floating-point number. It means that it gives 15-16 decimal digits precision. It consumes more memory in comparison to the float data type. It is used to store decimal values.

What is a double literal in Java?

Double Literals Are Not Unique Extra zeroes that don't change the value are not stored. Basically, Java converts these values to some internal format, where the additional zeroes don't play a factor.

What is double-precision floating point in Java?

The float and double primitive types in Java are floating point numbers, where the number is stored as a binary representation of a fraction and a exponent. More specifically, a double-precision floating point value such as the double type is a 64-bit value, where: 1 bit denotes the sign (positive or negative).


1 Answers

The problem is that very few decimals that you might type can be represented exactly as an IEEE float. So if you removed all non-exact constants you would make using double literals very unwieldy. Most of the time the behaviour of "pretend we can represent it" is far more useful.

like image 51
Flexo Avatar answered Oct 06 '22 07:10

Flexo