KnowItAllWannabe
KnowItAllWannabe

Reputation: 13512

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

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?

Upvotes: 23

Views: 969

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320481

If we restrict consideration to the "traditional" IEEE-754-style representation of floating-point types, then you can expect this conversion to be value-preserving if and only if the mantissa of the type double has as many bits as there are non-sign bits in type int.

Mantissa of a classic IEEE-754 double type is 53-bit wide (including the "implied" leading bit), which means that you can represent integers in [-2^53, +2^53] range precisely. Everything out of this range will generally lose precision.

So, it all depends on how wide your int is compared to your double. The answer depends on the specific platform. With 32-bit int and IEEE-754 double the equality should hold.

Upvotes: 12

Mysticial
Mysticial

Reputation: 471229

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.

Upvotes: 30

Related Questions