Error due to subtraction

Consider computing $$ x=10^{-8}, \qquad y = 1 - \cos(x) $$

In [1]:
from numpy import sin,cos
In [8]:
x = 1.0e-8
y = 1.0 - cos(x)
print "%24.14e" % y
    0.00000000000000e+00

Because of roundoff error, the result is zero. But mathematically we have the equivalent expression $$ z = 2 \sin^2(x/2) $$ which does not involve subtraction of nearly equal quantities.

In [10]:
z = 2.0*sin(0.5*x)**2
print "%24.14e" % z
    5.00000000000000e-17
In [ ]: