Search code examples
javafloating-pointfloating-accuracyfloating-point-precision

Java subtraction of floats is infinity?


In my debugger I can see the following values:

float min = -3.1931721E38
float max = 3.3434891E38

float temp = (max-min);

This results in infinity. Why is that? (2-2^23)·2^127 is larger than the temp variable right?


Solution

  • The mathematical result for this subtraction is larger than the largest possible Float value, Float.MAX_VALUE. Java follows the IEEE rules for floating-point arithmetic, which result in Infinity.

    If you want the result, then you can use doubles instead, which have greater precision and a far greater range of valid values.