-2

In C++, floor(9099.96 *100.0) is giving me the answer as 909995. I am expecting 909996.

I am not able to think of explanations here. Any help will be appreciated.Thanks.

sandy
  • 9
  • 2
  • 2
    Because floating point is never exact unless every number is a power of 2. And not always then. See http://stackoverflow.com/questions/1661273/floating-point-arithmetic-not-producing-exact-results – Gabe Sechan Aug 18 '14 at 05:02
  • @GabeSechan: 3.0 is exact and not a power of two. – rici Aug 18 '14 at 05:29
  • @rici I meant the fractional part is a multiple of 2. But to be picky, 3.0 won't always work either, if the exponent on the other number is so big it falls out into the error. – Gabe Sechan Aug 18 '14 at 05:46
  • 1
    @GabeSechan: 3.0 is always exact (as is 100.0), but the exact product of 3.0 or 100.0 with some other exact number might not be representable (because the exact representation has more than 52 bits.) I think that's what you meant. – rici Aug 18 '14 at 05:55
  • @rici Yeah, we both understand what we're talking about, and we're both right for how we were interpreting what we were talking about. Any whole number is always exact if it fits within the mantissa because the fractional part (the .0) is a negative power of two. – Gabe Sechan Aug 18 '14 at 05:59

2 Answers2

3

This is the proper result: according to IEEE754 calculator, the value of 9099.96 is represented as 9099.9599609375 in double. After multiplication by 100 you get 909995.99609375. Taking floor gives you 909995.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Thanks. I never knew even small floating point values gets approximated. – sandy Aug 18 '14 at 05:11
  • @sandy: *Not* approximating them would require infinite memory. – Keith Thompson Aug 18 '14 at 05:15
  • @sandy Only integers small enough to stay entirely within the bits mantissa are represented exactly. Even "simple" fractions such as `0.1` are inexact. For example, adding `0.1` to itself ten times in a loop does *not* produce a number that is equal to `1`. You get a value that's really, really close, but a small error would remain. – Sergey Kalinichenko Aug 18 '14 at 05:15
  • 1
    @dasblinkenlight - that's not quite true. 0.5, for instance, is exactly representable in both single- and double-precision. – Tom Aug 18 '14 at 06:43
0

Try ceil. It will always round the the next greatest number, which in this case will give you 909996. You may also want to look at the round function.

Pillager225
  • 439
  • 1
  • 3
  • 15
  • Thanks.But reading from above shared link, I think Ceil fails for other numbers. For example ceil(9099.95 *100.0) gives you 909996. – sandy Aug 18 '14 at 05:18