Skip to content

Zero is not Zero

3 messages · Thomas Lumley, Neil Klepeis

#
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 that some y's are not exactly zero as they should be.

Printing out pairs of x1 and y:
[Note the algorithm is finished when all y's are zero]

 > prec(c(1.1, 10, 120.34))
[1]   1.10  10.00 120.34
[1] 0.10 0.00 0.34

[1]  0.110  1.000 12.034
[1] 0.110 0.000 0.034

[1]   1.10  10.00 120.34
[1] 0.10 0.00 0.34

[1]   11.0  100.0 1203.4
[1] 0.0 0.0 0.4

# Here is the strange place where `x1-trunc(x1)' is not quite zero:

[1]   110  1000 12034
[1] 1.421085e-14 0.000000e+00 0.000000e+00

[1]   1100  10000 120340
[1] 0 0 0

# here is the highest precision, except it is *wrong*

[1] 0.001

---

Doing `110 - trunc(110)', of course gives "0" when entered on the R 
command-line directly:

 > 110 - trunc(110)
[1] 0

So where does that 1.421085e-14 come from, and how can I get rid of it?
#
On Thu, 31 Oct 2002, Neil Klepeis wrote:

            
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
#
I'm at a loss on this one:

 > c(1.253) %in% seq(1.1,1.3,by=0.001)
[1] FALSE
 > c(1.252) %in% seq(1.1,1.3,by=0.001)
[1] TRUE
 > c(1.254) %in% seq(1.1,1.3,by=0.001)
[1] TRUE


[R-1.6.0 Linux/Intel]