[R] Zero is not Zero

Thomas Lumley tlumley at u.washington.edu
Fri Nov 1 00:07:42 CET 2002


On Thu, 31 Oct 2002, Neil Klepeis wrote:

> I have a confusing problem with getting the form `x - trunc(x)' to be
> exactly zero when `x' is an integer. It only seems to occur inside of a
> function.  [R-1.6.0 on Linux/Intel]
>
> I have a function to return the highest precision digit of values in `x':
>
> prec<-function(x){
> init <- trunc(log10(max(x)))
> y <- x - trunc(x)
> while (any(y > 0)) {
>    init <- init - 1
>    x1 <- x*10^(-init)
>    y <- x1 - trunc(x1)
> }
> 10^init
> }
>

The problem is presumably that x1 isn't really an integer.  While
trunc(x1) should be exactly an integer there's no guarantee that there
exists a value of init such that x*(10^-init) is exactly an integer.

The following seems to do what you want:
prec<-function(x){
  init <- trunc(log10(max(x)))
  zero<- Machine()$double.eps*max(x)
  y <- x - trunc(x)
  while (any(y > zero)) {
    init <- init - 1
    x1 <- x*10^(-init)
    y <- x1 - trunc(x1)
  }
  10^init
}

	-thomas

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list