Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is int->double->int guaranteed to be value-preserving?

Tags:

If I have an int, convert it to a double, then convert the double back to an int, am I guaranteed to get the same value back that I started with? In other words, given this function:

int passThroughDouble(int input) {   double d = input;   return d; } 

Am I guaranteed that passThroughDouble(x) == x for all ints x?

like image 357
KnowItAllWannabe Avatar asked Dec 03 '12 22:12

KnowItAllWannabe


People also ask

Can you store an integer into a double?

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.

Can we convert int to double in C?

The %d format specifier expects an int argument, but you're passing a double . Using the wrong format specifier invokes undefined behavior. To print a double , use %f .

Can we add integer and double in Java?

In Java, integer addition and double addition use different hardware. Even though they may seem the same to you, they are actually quite different to the computer. The computer wants to either add two int values or two double values. Java's solution (as in many other languages) is type promotion.

Can we assign a float variable to a long integer variable?

You can safely assign a floating point variable to an integer variable, the compiler will just truncate (not round) the value. At most the compiler might give you a warning, especially if assigning from e.g. a double or bigger type.


1 Answers

No it isn't. The standard says nothing about the relative sizes of int and double.

If int is a 64-bit integer and double is the standard IEEE double-precision, then it will already fail for numbers bigger than 2^53.


That said, int is still 32-bit on the majority of environments today. So it will still hold in many cases.

like image 133
Mysticial Avatar answered Oct 11 '22 01:10

Mysticial