[R] acos(0.5) == pi/3 FALSE
(Ted Harding)
Ted.Harding at nessie.mcc.ac.uk
Tue Sep 19 00:05:05 CEST 2006
On 18-Sep-06 Iñaki Murillo Arcos wrote:
> Hello,
>
> I don't know if the result of
>
> acos(0.5) == pi/3
>
> is a bug or not. It looks strange to me.
>
> Inaki Murillo
It is not a bug, but a feature, in that acos(0.5) and pi/3
are not computed in the same way, so (because of the small
inaccuracies inevitable in their finite representations)
they are indeed not equal; and this is what R is telling you.
acos(0.5) - pi/3
[1] 2.220446e-16
The difference, as you can see is very small. However, if
for some reason (e.g. in the logic of a programming branch
which depends on such a comparison) then you could make it
work by computing them in the same way:
pi<-3*acos(0.5)
acos(0.5) - pi/3
[1] 0
I.e. redefine pi in R so that its computation is compatible
with that of acos(0.5) (but this pi is only in the current
environment).
However, the usual way of comparing two numbers which should
theoretically be equal, but might differ slightly when computed
in R, is to use
all.equal(x, y)
See "?all.equal". Also see "?identical".
all.equal(acos(0.5),pi/3)
[1] TRUE
(Here I'm using R's "default" value of pi, not the value
I defined above).
all.equal(x,y) tests whether x and y differ by more than
a tolerance which by default is .Machine$double.eps but
which can be set to something else if you wish.
Best wishes,
Ted.
--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 18-Sep-06 Time: 23:05:01
------------------------------ XFMail ------------------------------
More information about the R-help
mailing list