-1

I have the following code.

public class ToBeDeleted {

    public static final float MAX_PHYSICAL_LENGTH = 100000000;

    public static void main(String[] args) {
                    //100000000
        float temp = 100000000 -4;

        System.out.println(temp);

        if (MAX_PHYSICAL_LENGTH == temp)
            System.out.println("True statement");
        else
            System.out.println("False Statement");

    }

}

The output of the above is

1.0E8
True statement

Now with the below code

public class ToBeDeleted {

    public static final float MAX_PHYSICAL_LENGTH = 100000000;

    public static void main(String[] args) {
                    //100000000
        float temp = 100000000 -5;

        System.out.println(temp);

        if (MAX_PHYSICAL_LENGTH == temp)
            System.out.println("True statement");
        else
            System.out.println("False Statement");

    }

}

The output is

9.9999992E7
False Statement

The question is

  1. Whats wrong with the first code snip. Is this not plain mathematics as far as float is concerned?
  2. Why does it then give the expected output on the second code snip.
TheMonkWhoSoldHisCode
  • 2,182
  • 3
  • 26
  • 40
  • 1E8 has an exponent of 2^26, so the lsb of the significand has a weight of 8. If you subtract 4, "round to nearest even" means up (1E8 has lsb=0), if you subtract 5 it rounds down. – harold Apr 04 '17 at 12:25
  • 1
    All formats have limitations, including limited precision. Infinite precision only exists in mathematics, not the real world. – Peter Lawrey Apr 04 '17 at 13:57

1 Answers1

3

A typical (i.e. IEEE754) float only has 23 bits of precision. The other bits are for the exponent and the sign. The lowest integer that you can't store exactly is 1 plus the 24th power of 2.

100000000 - 4 is indistinguishable from 100000000 - 0.

A Java double gives you 52 bits of precision, therefore enough space to store all integers exactly up to the 53rd power of 2.

For more details see Which is the first integer that an IEEE 754 float is incapable of representing exactly?

But if you need exact decimal accuracy, then use a decimal type.

Community
  • 1
  • 1
Bathsheba
  • 231,907
  • 34
  • 361
  • 483