2

May I assume that (int)(float)n == n for any int n? At least I need this for non-negative, 31 bits values.

addendum. What about (int)(double)n ==n?

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
Emanuele Paolini
  • 9,912
  • 3
  • 38
  • 64
  • 2
    if n is already int, why cast? – Mitch Wheat Jan 03 '14 at 09:24
  • My ints go into an array of floats for some computation. – Emanuele Paolini Jan 03 '14 at 09:25
  • I'd suggest you try this program: http://ideone.com/iADlOt – nos Jan 03 '14 at 09:26
  • @haccks Why wouldn't this compile? –  Jan 03 '14 at 09:29
  • Very closely related questions: http://stackoverflow.com/questions/3793838/which-is-the-first-integer-that-an-ieee-754-float-is-incapable-of-representing-e and http://stackoverflow.com/questions/13269523/can-all-32-bit-ints-be-exactly-represented-as-a-double – Chris Culter Jan 03 '14 at 09:30
  • @haccks If you read the program, you would realize that it outputs all floats for which a conversion from int to float and back again does not preserve the value. i.e. it prints all n for which (int)(float)n != n , demonstrating the that the assumption of the OP is false. – nos Jan 03 '14 at 09:31
  • @H2CO3; Sorry for the comment. I misread `==` as `=`. – haccks Jan 03 '14 at 09:33
  • @nos; In fact I was curious about the variable initialization. (which are already initialized in that program, did't noticed that). – haccks Jan 03 '14 at 09:34

1 Answers1

10

No, you can't. For ints that can't be represented exactly by a float, this will fail.

(The reason: float is generally a 32-bit IEEE-754 floating-point value. It only has 24 bits of precision, the rest is reserved for the exponent and the sign. So if your integer has more significant binary digits than 23, and it doesn't happen to be a multiple of an appropriate power of two, then it can't be represented precisely as a float.)

addendum. What about (int)(double)n ==n?

It's the same. For ints that can't be represented as a double, the comparison won't always yield true. However, generally, int is not long enough to accomplish this -- the widely-accepted implementation of double is a 64-bit IEEE-754 floating-point number which has 53 bits of precision, whereas ints tend to be at most 32 bits long. But you can always try to repeat the experiment with a long or a long long and a double instead.

Here's a demo:

#include <stdio.h>

int main()
{
    int n = (1 << 24) + 1;

    printf("n == n: %d\n" , n == n);
    printf("n == (int)(float)n: %d\n", n == (int)(float)n);

    return 0;
}

This prints:

n == n: 1
n == (int)(float)n: 0