Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can every float be expressed exactly as a double?

Can every possible value of a float variable can be represented exactly in a double variable?

In other words, for all possible values X will the following be successful:

float f1 = X;
double d = f1;
float f2 = (float)d;

if(f1 == f2)
  System.out.println("Success!");
else
  System.out.println("Failure!");

My suspicion is that there is no exception, or if there is it is only for an edge case (like +/- infinity or NaN).

Edit: Original wording of question was confusing (stated two ways, one which would be answered "no" the other would be answered "yes" for the same answer). I've reworded it so that it matches the question title.

like image 503
Kip Avatar asked Nov 03 '08 15:11

Kip


People also ask

Is a float the same as a double?

float and double both have varying capacities when it comes to the number of decimal digits they can hold. float can hold up to 7 decimal digits accurately while double can hold up to 15.

Can double represent all integers exactly?

Short answer is "no" - the range of values an int can represent and that a double can represent are implementation defined - but a double certainly cannot support every integral value in the range it can represent.


2 Answers

Yes.

Proof by enumeration of all possible cases:

public class TestDoubleFloat  {
    public static void main(String[] args) {
        for (long i = Integer.MIN_VALUE; i <= Integer.MAX_VALUE; i++) {
            float f1 = Float.intBitsToFloat((int) i);
            double d = (double) f1;
            float f2 = (float) d;
            if (f1 != f2) {
                if (Float.isNaN(f1) && Float.isNaN(f2)) {
                    continue; // ok, NaN
                }
                fail("oops: " + f1 + " != " + f2);
            }
        }
    }
}

finishes in 12 seconds on my machine. 32 bits are small.

like image 96
mfx Avatar answered Sep 30 '22 18:09

mfx


In theory, there is not such a value, so "yes", every float should be representable as a double.. Converting from a float to a double should involve just tacking four bytes of 00 on the end -- they are stored using the same format, just with different sized fields.

like image 22
James Curran Avatar answered Sep 30 '22 19:09

James Curran