Search code examples
rfloor

Floor not giving expected results when passed a calculation


Why does only A out of A and B below equal 29? What is different about using a calculation as the x argument?

#A
floor(x = (1.45/0.05))
#B
floor(x = 29)

> #A
> floor(x = (1.45/0.05))
[1] 28
> #B
> floor(x = 29)
[1] 29

Solution

  • Like @bouncyball indicated it is a floating point problem.

    If you go for example to this link and enter 1.45 or 0.05 you will notice that their binary representations are "infinitely" long (i.e. you can't write 1.45 with a finite string in binary).
    Because your PC doesn't have infinite storage to store the digit he "chops" it off at some point - meaning he basically has your 1.45 as something like 1.49999999999 (nevermind the number of 9s) in his system. The same happens for 0.05.

    Now your computer internally gets something like 28.9999999999999 - but he's not stupid when he outputs it. He knows, well 28.9999999999 is probably supposed to be 29 - so when he outputs it he just rounds. Except when you tell him explicitly to round using "floor" - then he rounds 28.99999999 to 28.
    Hope that makes sense.