4

I have tried to output following but got confused,

    float f=3.4;
    char *cp;
    cp=(char *)&f;
    printf("%d\n",*cp);

normalized number I have calculated IEEE 754 std is,

0 10000000 10110011001100110011001

that's why I assumed at cp now value has,

10011001

after convert to 2's complement,

01100111

It should output -103 , but I got -102 in my bloodshed/DevC. why such output???

reuben
  • 3,360
  • 23
  • 28
amin__
  • 1,018
  • 3
  • 15
  • 22

2 Answers2

4

That's because f is being rounded up:

3.4 = 10110011001100110011001 100110011001...  (repeating 1001)

rounds up to:

3.4 = 10110011001100110011010
                            ^

when stored into single-precision floating-point.

Now when you extract out the last 8 bits, you're actually getting 10011010 instead of 10011001.

Converting 10011010 -> -102 instead of -103.

Mysticial
  • 464,885
  • 45
  • 335
  • 332
  • when should I consider a rounding up? If there was a `0` after the last mantissa bit, would I round this up or only just when there is a `1` after last mantissa bit as this example?? – amin__ Jul 07 '12 at 20:00
  • 1
    The exact rules are tricky since you have to respect round-to-even. But in this case, yes there is a 1 after the last mantissa bit. So it rounds up. – Mysticial Jul 07 '12 at 20:01
  • I am curious to know, is this rule is same for double-precision floating point?? – amin__ Jul 07 '12 at 20:05
  • Yes, that's correct. It's the same for IEEE double-precision. – Mysticial Jul 07 '12 at 20:06
  • can you tell me how many mantissa bits in 32-bit and 64-bit floating point has?? I read they are 23 and 52 respectively, but in this link i found they are 24 and 53, http://stackoverflow.com/questions/3962724/problems-in-floating-point-comparison. Is this for different representation or what?? – amin__ Jul 09 '12 at 14:51
  • @amin__ There's an implicit 1-bit that isn't stored in the representation. (See: http://en.wikipedia.org/wiki/Single-precision_floating-point_format) Same applies to double-precision. – Mysticial Jul 09 '12 at 15:05
2

I think you miscalculated:

Prelude> decodeFloat (3.4 :: Float)
(14260634,-22)
(0.03 secs, 2929112 bytes)
Prelude> Numeric.showHex (fst it) ""
"d9999a"

The mantissa ends in 1010.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
  • I have calculated again. Am I miscalculating or it is rounding up ?? please see Mysticial's answer..I want to know what is happening? – amin__ Jul 07 '12 at 19:58
  • 1
    It's rounded up. The infinite representation continues `1001|10011001...` where the `|` marks the end of the `float`. Since the remainder is larger that half an ULP, it gets rounded up (it would also get rounded up here if the remainder were exactly half an ULP, because the standard rounding mode is round-to-last-bit-zero for remainders of half an ULP). – Daniel Fischer Jul 07 '12 at 20:02
  • would you please clarify half of ULP for me. I am seeing that term first. please.. – amin__ Jul 07 '12 at 20:11