[R] seq(0.05,0.95,by=0.002) and logical error

Ray Brownrigg Ray.Brownrigg at mcs.vuw.ac.nz
Sun Dec 10 21:30:54 CET 2000

```| That's a computational problem:
|
|   jj <- seq(0.05, 0.95, by=0.002)
|   options("digits" = 22)
|   jj[351]  # result:  [1] 0.75000000000000011
|
| So sum(jj==0.75) gives the *correct* answer.
|
Also note that:
> jj <- seq(50, 950, by=2)/1000
> sum(jj==0.75)
[1] 1
>
will (should!) always give the answer you require.

The problem is that .002 is not *exactly* .002, and (more generally),
decimal floating point numbers cannot in general be represented exactly
in binary.

> > sum(jj==0.562)
> [1] 1
> > sum(jj==0.564) ## 0.564 seems to be the cutoff point
> [1] 0

This is not quite the true situation. The 'correct' values are scatterd
throughout the vector jj:

> kk <- seq(50, 950, by=2)/1000	# generate 'correct' values
> ll <- as.numeric(jj==kk)
> ll
[1] 1 0 0 1 1 0 1 1 1 1 1 0 0 0 1 1 1 1 0 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0
[38] 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1
[75] 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
[112] 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1
[149] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1
[186] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1
[223] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0
[260] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1
[297] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[334] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
[371] 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[408] 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
[445] 0 0 0 0 0 0 0
> sum(ll)
[1] 296
>
So more than 60% of them are 'correct'.

Hope this helps,
Ray Brownrigg
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```