0

The floor method of class Float returns the next integer for large float values of only 9.

Why is that?

irb(main):041:0> (100.67893).floor
=> 100
irb(main):042:0> (100.99999999999999999).floor
=> 101
irb(main):043:0> (99.9999999).floor
=> 99
irb(main):044:0> (99.9999999999999999999).floor
=> 100
arjun
  • 1,594
  • 16
  • 33
  • Technically for any integer x, x.999...... is equal to x + 1. In this case, floating point data types can't represent it accurately so it's actually just 100. – Andrew Li Mar 26 '17 at 19:56
  • The thing is it only happens with repeating `9` values. Not with any other equally large or mixed values. Try this `(100.989898989898998989989899898989898989899898989).floor` – arjun Mar 26 '17 at 19:57
  • 2
    This has nothing at _all_ to do with `Float#floor`; just `99.9999999999999999999` by itself evaluates to `100.0`, presumably because the difference between the two values is too small to represent in a standard floating point value. This definitely looks like [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) to me. – philomory Mar 26 '17 at 20:15
  • @arjun : Yes, because this float is stricly less than `100.990`, so the difference to `101` is much larger than float epsilons. Ruby can tell it's nowhere near `101`, so `floor` is `100` – Eric Duminil Mar 26 '17 at 20:15
  • @philomory That's fine. Couldn't have find it for Ruby. – arjun Mar 26 '17 at 20:22
  • The number preceding `101.0` is `100.99999999999999` (call `101.0.prev_float`). If you append another `9`, the result will be closer to `101.0` than to `100.99999999999999` and Ruby will hence return `101.0`. – Stefan Mar 27 '17 at 08:04

0 Answers0