mysterious behavior of == in R language

Asked 1 months ago, Updated 1 months ago, 2 views

>cos(pi/4)
[1] 0.7071068
>sin(pi/4)
[1] 0.7071068
>cos(pi/4)==sin(pi/4)
[1] FALSE

I think it can't be helped because it's an unreasonable number, but

>cos(pi/3)
[1] 0.5
>sin(pi/6)
[1] 0.5
>cos(pi/3)==sin(pi/6)
[1] FALSE

Thus, even if the values are the same among rational numbers, they are not considered equal.What kind of explanation is possible?By the way,

>(sqrt(2)))^2
[1] 2
>(sqrt(2))^2 == 2
[1] FALSE

Thus, even if the values are the same among integers, they may not be considered equal.Please let me know your generalization.

r

2022-09-30 11:59

2 Answers

This is an explanation from R's official FAQ.

7.31 Why doesn't R think these numbers are equal?

The only numbers that can be presented exactly in R's numeric type
are integers and effects where denominator is a power of 2. Other
numbers have to be round to (typically) 53 binary digits acuity.
As a result, two floating point numbers will not be relatable be equal
unless they have been compiled by the same algorithm, and not always
even then.

In R, only integers and fractions whose denominators are で of 2 can be accurately represented.Other numbers are rounded (typically) to 53 binary accuracy.
As a result, the two floating-point numbers will not and in some cases even be guaranteed to be equal unless calculated by the same algorithm.


2022-09-30 11:59

The R number is a floating point, so you should be careful the same as the floating point comparison in a typical programming language.

>sin(pi/6) - 0.5
[1] - 5.551115e-17
>cos(pi/3) - 0.5
[1] 1.110223e-16

As shown in , the comparison is FALSE because it is actually a different number.

A common method is to determine the tolerance in advance and include it.

>epsilon<-1e-10
>abs(sin(pi/6)-cos(pi/3))<=epsilon
[1] true

In the following question post, there was also a suggestion that you prepare your own comparison functions that take into account these errors.

cf.floating point-Numerical comparison differential in R-Stack Overflow


2022-09-30 11:59

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.