[R] Fractional component of a number

(Ted Harding) ted.harding at wlandres.net
Sun Aug 28 10:24:17 CEST 2011


On 28-Aug-11 03:59:51, edward.m at psu.ac.th wrote:
> Dear all,
> I am happy to accept that
> 
>> is.integer(1)
> [1] FALSE
> 
> But I'm having difficulty with this one:
> 
>> as.integer((2.53-2)*100)
> [1] 52
> 
> especially since:
> 
>> as.integer((1.53-1)*100)
> [1] 53
> 
> Although I know that this is a precision issue since
> 
>> x <- (2.53-2)*100
>> x-53
> [1] -2.131628e-14
> 
> And I can always use the round function to get what I want,
> but I just wonder if something is wrong here.
> 
>> sessionInfo()
> R version 2.13.1 (2011-07-08)
> Platform: i386-pc-mingw32/i386 (32-bit)
> 
> locale:
> [1] LC_COLLATE=Thai_Thailand.874  LC_CTYPE=Thai_Thailand.874   
> LC_MONETARY=Thai_Thailand.874
> [4] LC_NUMERIC=C                  LC_TIME=Thai_Thailand.874
> 
> attached base packages:
> [1] stats     graphics  grDevices utils     datasets  methods   base
> 
> Thanks,
> Edward

It depends on what you mean by "wrong"! Perhaps "unexpected"
might be better!

The key to the matter is described in '?as.integer' under "Value":

  Non-integral numeric values are truncated towards zero
  (i.e., ?as.integer(x)? equals ?trunc(x)? there) ...

so that

  as.integer(2)
  # [1] 2
  as.integer(2 + 2e-14)
  # [1] 2
  as.integer(2 - 2e-14)
  # [1] 1
  as.integer(-2 + 2e-14)
  # [1] -1
  as.integer(-2 - 2e-14)
  # [1] -2


so it is doing "what it says on the box". Yes, you are better
using round()!

Hoping this helps to clear it up,
Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <ted.harding at wlandres.net>
Fax-to-email: +44 (0)870 094 0861
Date: 28-Aug-11                                       Time: 09:24:14
------------------------------ XFMail ------------------------------



More information about the R-help mailing list