[R] Strange behaviour of as.integer()
Martin Maechler
maechler at stat.math.ethz.ch
Mon Jan 11 16:37:44 CET 2010
>>>>> "MT" == Magnus Torfason <zulutime.net at gmail.com>
>>>>> on Thu, 07 Jan 2010 10:01:28 -0500 writes:
MT> There have been some really great responses to this question. I would
MT> like to make a minor contribution by throwing the 'gmp' package into the
MT> mix.
MT> On 1/7/2010 8:12 AM, Duncan Murdoch wrote:
>> On 07/01/2010 7:31 AM, Ulrich Keller wrote:
>>>> as.integer(.57 * 100)
>>> [1] 56
>>
>> Yes, as the man page states, non-integer values are truncated towards
>> zero.
>>
>> > .57*100 < 57
>> [1] TRUE
MT> gmp provides the bigz and bigq classes which provide arbitrary precision
MT> integers and rationals, and would solve Ulrich's original
MT> problem quite effectively:
>> library(gmp)
>>
>> # bigq will not parse "0.57" but writing such a parser
>> # would be a trivial extension.
>> x = as.bigq("57")/100
>> x
MT> [1] "57/100"
>>
>> # as.integer(x*100) does not seem to be overloaded correctly, so
>> # we need to use as.numeric first, but the end result is 57
>> as.integer(as.numeric(x*100))
MT> [1] 57
>>
>> # And we conclude by making some comparisons, and finding the that
>> # the results are what a fifth-grader would expect, rather than
>> # what a CS grad would expect :-)
>> x*100<57
MT> [1] FALSE
>> x*100==57
MT> [1] TRUE
MT> Of course there is still the problem that:
>> 1+1 == sqrt(2)*sqrt(2)
MT> [1] FALSE
MT> and gmp will not solve this . I don't know if there is an R-package for
MT> arbitrary-precision reals floating around, but probably not.
Yes, there's package 'Rmpfr' for arbitrary precision
floating-point, written and maintained by me.
As it is based on the (GNU) library MPFR which itself is based
on the GNU MP (=: GMP) library, for Windows the Rmpfr package is
currently not available from CRAN, but thanks to Brian Ripley
from his CRANextras collection.
However, that does *still* not allow the equivalent
of
1+1 == sqrt(2)*sqrt(2)
because that would need *infinite* precision not just arbitrary
precision, or then *symbolic* computation, as I assume the following does
MT> However, Wolfram Alpha will return the correct answer:
MT> http://tr.im/1plus1equals2
BTW: I see that I seem to have forgotten to upload the
somewhat newer and better R-forge version of Rmpfr to CRAN,
something to be done "Real Soon Now".
In the mean time, you can use
install.packages("Rmpfr", repos="http://R-Forge.R-project.org")
which -- thanks to Stefan Theussl as R-forge maintainer -- may
even on Windows give a working version of Rmpfr.
Martin Maechler, ETH Zurich
More information about the R-help
mailing list