[R] Why does sin(pi) not return 0?
Martin Maechler
maechler at lynne.ethz.ch
Thu Sep 26 16:17:39 CEST 2013
>>>>> Suzen, Mehmet <msuzen at gmail.com>
>>>>> on Thu, 26 Sep 2013 14:48:52 +0200 writes:
> On 26 September 2013 11:30, Rainer M Krug <Rainer at krugs.de> wrote:
>>>>> Why doesn't return me 0?
> It isn't R question at all. You might want to read about representing
> real numbers in a computer using floating point
> http://en.wikipedia.org/wiki/Floating_point
> If you want more precision for some reason, you may want to use Rmpfr
> package from CRAN, for example
>> require(Rmpfr)
>> pii <- mpfr(pi, 1200)
>> sin(pii)
> 1 'mpfr' number of precision 1200 bits
> [1] 1.22464679914735317722606593227499799708305390129979194948825771626086960997325810377509325527569013655456428540074414189136673810003656057935764118217436637676835016019778833613838580470703060741630570066750947925902443295873487819032259435513861185501796412843027607796970259523768923503206248925733373776859085615900203929142965774524665617260404787862664073939e-16
Thank you, Suzen, for mentioning Rmpfr.
In that case, I think you should also show how to get a more
accurate approximation of 0:
The most convenient way with Rmpfr is to use the builtin pi, in
the following :
> pii <- Const("pi") # default precision of 120 bits
> sin(pii)
1 'mpfr' number of precision 120 bits
[1] -5.5059930380881434362856026294599943387e-37
> ## or
> pii <- Const("pi", prec = 240)
> pii
1 'mpfr' number of precision 240 bits
[1] 3.1415926535897932384626433832795028841971693993751058209749445923078164072
## and indeed the above is pi accurate to about 74 decimal digits
> sin(pii)
1 'mpfr' number of precision 240 bits
[1] -8.9200160854418520294613808989866371392121893805952954481681649396960358864e-73
> asNumeric(sin(pii))
[1] -8.920016e-73
>
So you see, the more accurate the approximation pii for the true
\pi, the more accurate is the result of sin(pii)
Martin Maechler, ETH Zurich
(and author of Rmpfr)
More information about the R-help
mailing list