[R] Rounding problem R vs Excel

Mike White mikewhite.diu at tiscali.co.uk
Tue Jun 3 10:49:44 CEST 2003


Duncan
If the numbers are not represently exactly how does R resolve problems like
the one below? Is there something that needs to be set up in the R
environment like the number of significant figures?

> x<-4.145*100+0.5
> x
[1] 415
> floor(x)
[1] 414
> as.integer(x)
[1] 414
> trunc(x)
[1] 414

Mike White
----- Original Message -----
From: "Duncan Murdoch" <dmurdoch at pair.com>
To: "Hedderik van Rijn" <hedderik at cmu.edu>
Cc: <R-help at stat.math.ethz.ch>
Sent: Tuesday, June 03, 2003 2:40 AM
Subject: Re: [R] Rounding problem R vs Excel


> On Mon, 2 Jun 2003 20:50:20 -0400, you wrote:
>
> >Does this script do what you want?
> >
> >cround <- function(x,digits=0) {
> >   a <- ifelse(x>0,.5,-.5)
> >   if (digits==0) {
> >     floor(x+a)
> >   } else {
> >     m <- 10^digits
> >     floor(x*m+a)/m
> >   }
> >}
>
> No, the problem is that R uses binary formats, and some numbers aren't
> representable there.  So for example,
>
> > cround(0.145,2)
> [1] 0.14
>
> because 0.145 isn't representable exactly, and is actually being
> represented as 0.14999999999 or something similar.
>
> Duncan Murdoch
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>
>




More information about the R-help mailing list