[R] trunc/floor a number -- strange bahaviour

Duncan Murdoch murdoch at stats.uwo.ca
Thu Feb 12 16:44:32 CET 2009


On 2/12/2009 10:20 AM, Žroutík wrote:
> Hi everybody,
> 
> given a fresh rgui.exe load on winxp OS, I enter (a minimal exaple)
> 
> n <- 12.357531
> 
> Then the following command:
> n <- (n - floor(n))*10; n
> 
> gives the following outputs:
> [1] 3.57531
> [1] 5.7531
> [1] 7.531
> [1] 5.31
> [1] 3.1
> [1] 1         === still as expected
> [1] 10        === not expected, count with me: 1 - floor(1) is zero, times
> 10 gives 0, not 10!!!!

You are assuming that when R prints "1", the value is exactly 1.  But 
try this:

 > 0.999999999
[1] 1
 > 0.999999999 == 1
[1] FALSE

R rounds values when it prints them, because people don't want to see 
ugly output like this:

 > options(digits=18):
 > n <- 12.357531
 > n <- (n - floor(n))*10; n
[1] 3.5753100
 > n <- (n - floor(n))*10; n
[1] 5.75309999999998
 > n <- (n - floor(n))*10; n
[1] 7.530999999999821
 > n <- (n - floor(n))*10; n
[1] 5.30999999999821
 > n <- (n - floor(n))*10; n
[1] 3.099999999982117
 > n <- (n - floor(n))*10; n
[1] 0.999999999821171

And the reason you see such ugly output is because you are working with 
a number that can't be represented exactly in binary floating point.

Duncan Murdoch

> [1] 10        === should stay forever zero (0)
> [1] 10
> [1] 9.999998
> [1] 9.999982
> [1] 9.999821
> [1] 9.998212
> 
> The sama happens with trunc().
> e.g. (a minimal exaple)
> 
> n <- 0.245
> n <- (n - trunc(n))*10; n
> [1] 2.45
> [1] 4.5
> [1] 5
> [1] 1.776357e-13 ===== zero expected!!!
> [1] 1.776357e-12
> 
> And I'm asking "what the heck?!" and where is the bug in my examples? Any
> suggestion well appreciated.
> 
> p.s. The expression with floor() and trunc() are to be implemented in a
> function which gives a value equal precision order of the given number. e.g.
> 12.345 would have (-3), 12.1 would have (-1), 12 would have (0) and e.g.
> 12000 would have the order of the precision (4). Basically, it is the order
> of the last given non-zero digit.
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list