0

I came to interesting problem when dealing with Java primitive type float

I try to subtract 1.0 from Float.MAX_VALUE, strangely it returns the value equals Float.MAX_VALUE. Here is an example:

  float floatMaxValue = Float.MAX_VALUE;
  float subtractedMaxValue = Float.MAX_VALUE - 1.0f;

  System.out.println(floatMaxValue);
  System.out.println(subtractedMaxValue);
  Assert.assertTrue(floatMaxValue == subtractedMaxValue); // return true even false expected

Could someone explain me why this happens? I guess is some magic with floating point.

Stefan Repcek
  • 2,553
  • 4
  • 21
  • 29
  • You don't need to go as far as `MAX_VALUE` - try `1 << 25`. – Oliver Charlesworth Mar 25 '18 at 18:33
  • You seem to think that a `float` can represent all integral values at the top of its range - this is not true. See [here](https://stackoverflow.com/a/1848762/2071828) for an explanation of this for `double`. – Boris the Spider Mar 25 '18 at 18:34
  • The precision of `float` is limited to around 6 digits. When you subtract one and take the nearest representable value you get the one you started with. It's basically the same as doing `int i = 1; i -= 0.1;` and see that `i` didn't change. There is nothing magic about floating point, it just has limitations. – Peter Lawrey Mar 25 '18 at 18:43

0 Answers0