#!/usr/bin/env python # coding: utf-8 # # Error due to subtraction # In[11]: from math import sin,cos # ## Example 1 # Consider computing # $$ # x=10^{-8}, \qquad y = 1 - \cos(x) # $$ # In[12]: x = 1.0e-8 y = 1.0 - cos(x) print("%24.14e" % y) # Because of roundoff error, the result is zero. But mathematically we have the equivalent expression # $$ # x = 10^{-8}, \qquad z = 2 \sin^2(x/2) # $$ # which does not involve subtraction of nearly equal quantities. # In[13]: z = 2.0*sin(0.5*x)**2 print("%24.14e" % z) # ## Example 2 # $$ # x=10^{-8}, \qquad y = \frac{1 - \cos(x)}{x^2} # $$ # In[14]: y = (1.0 - cos(x))/x**2 print("%24.14e" % y) # $$ # x=10^{-8}, \qquad z = \frac{2 \sin^2(x/2)}{x^2} # $$ # In[15]: z = 2.0*sin(0.5*x)**2 / x**2 print("%24.14e" % z)