Вопрос

I wonder why this statement is evaluated false:

>>> from numpy import sin,cos,pi
>>> sin(pi/4)==cos(pi/4)
False

in fact sine and cosine of pi/4 should be √ 2 / 2. What's happen? And how to avoid this problem?

Это было полезно?

Решение

If you look at what the results actually are:

>>> sin(pi/4)
0.70710678118654746
>>> cos(pi/4)
0.70710678118654757

You will note that they are very, very close, but not exactly the same. Due to these kinds of floating point representation issues, it is usual to use a threshold to compare values that should be the same:

>>> abs(sin(pi/4) - cos(pi/4)) < 1e-9
True

Fun fact: using numpy's sqrt, too:

>>> sqrt(2)/2
0.70710678118654757
>>> sqrt(2)/2 == cos(pi/4)
True

Другие советы

Because floating point representation isn't always exact and functions like cos and sin are calculated by approximate numerical methods, it is unreasonable to imagine that the results will be bitwise identical. On my machine, I get this when I compare sine and cosine

>import numpy
>x=numpy.sin(numpy.pi/4)
>y=numpy.cos(numpy.pi/4)
>print numpy.abs(x-y)/numpy.max(x,y)
1.57009245868e-16

ie. the relative error is very close to the IEEE 754 double precision epsilon. If you need to compare two floating point values, compare a delta value to a tolerance, or use numpy.allclose()

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top