CompEcon Toolbox:
DemApp06
Chebychev and cubic spline derivative approximation errors
Randall Romero Aguilar, PhD

This demo is based on the original Matlab demo accompanying the Computational Economics and Finance 2001 textbook by Mario Miranda and Paul Fackler.

Last updated: 2020-Sep-08

In [ ]:
if 'google.colab' in str(get_ipython()):
print("This notebook is running on Google Colab. Installing the compecon package.")
!pip install compecon

In [ ]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from compecon import BasisChebyshev, BasisSpline, nodeunif, demo


### Function to be approximated¶

In [ ]:
f = lambda x: np.exp(-x)
df = lambda x: -np.exp(-x)
d2f = lambda x: np.exp(-x)


Set degree of approximation and endpoints of approximation interval

In [ ]:
a =  -1  # left endpoint
b =   1  # right endpoint
n =  10  # order of interpolatioin


Construct refined uniform grid for error ploting

In [ ]:
x = np.linspace(a,b, 1001)


Construct Chebychev interpolant

In [ ]:
C = BasisChebyshev(n, a, b, f=f)


Construct cubic spline interpolant

In [ ]:
S = BasisSpline(n, a, b, f=f)


### Plot function approximation error¶

In [ ]:
y = f(x)

fig1, axs = plt.subplots(2,1,sharex=True)
fig1.suptitle('Function Approximation Error')

(pd.DataFrame({
'Chebychev': y - C(x),
'Cubic Spline': y - S(x)},
index=x)
.plot(subplots=True, ax=axs)
);


### Plot first derivative approximation error¶

In [ ]:
dy = df(x)

fig1, axs = plt.subplots(2,1,sharex=True)
fig1.suptitle('First Derivative Approximation Error')

(pd.DataFrame({
'Chebychev': dy - C(x, 1),
'Cubic Spline': dy - S(x, 1)},
index=x)
.plot(subplots=True, ax=axs)
);


### Plot second derivative approximation error¶

In [ ]:
d2y = d2f(x)

fig1, axs = plt.subplots(2,1,sharex=True)
fig1.suptitle('Second Derivative Approximation Error')

(pd.DataFrame({
'Chebychev': d2y - C(x, 2),
'Cubic Spline': d2y - S(x, 2)},
index=x)
.plot(subplots=True, ax=axs)
);