Demonstrates the effect of roundoff error when evaluating
(x-1)^6 near x=1.
import numpy as np
import matplotlib.pyplot as plt
# Set up some vectors of x-values
x_wide = np.linspace(0,2,10001)
x_narrow = np.linspace(0.995,1.005,501)
# Evaluate using Method 1 (factored version)
y1_wide = (x_wide-1.)**6
y1_narrow = (x_narrow-1.)**6
# Evaluate using Method 2 (expanded version)
x = x_wide
y2_wide = x**6 -6*x**5 + 15*x**4 -20*x**3 + 15*x**2 - 6*x + 1
x = x_narrow
y2_narrow = x**6 -6*x**5 + 15*x**4 -20*x**3 + 15*x**2 - 6*x + 1
# Plot the full (wide) domain
plt.figure(1)
plt.clf()
plt.subplot(1,2,2)
plt.plot(x_wide,y2_wide)
plt.xlabel('x')
plt.title('(x-1)^6')
v = plt.axis()
plt.subplot(1,2,1)
plt.plot(x_wide,y1_wide)
plt.xlabel('x')
plt.title('Expanded')
plt.axis(v);
# Plot the narrow domain
plt.figure(2,figsize=(18,8))
plt.clf()
plt.subplot(1,2,2)
plt.plot(x_narrow,y2_narrow)
plt.xlabel('x')
plt.title('Expanded')
v = plt.axis()
plt.subplot(1,2,1)
plt.plot(x_narrow,y1_narrow)
plt.xlabel('x')
plt.title('(x-1)^6')
plt.axis(v);