CompEcon Toolbox:
DemQua03
Area under 1-D and 2-D curves, various methods
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-10

Uni- and bi-vaiariate integration using Newton-Cotes, Gaussian, Monte Carlo, and quasi-Monte Carlo quadrature methods.

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
from compecon import qnwtrap, qnwsimp, qnwlege, demo
import matplotlib.pyplot as plt
import pandas as pd

In [ ]:
quadmethods = [qnwtrap, qnwsimp, qnwlege]


### Make support function¶

In [ ]:
a, b = -1, 1
nlist = [5, 11, 21, 31]
N = len(nlist)

xi, wi = qnw(n,a,b)
return np.dot(func(xi),wi)


## Evaluating¶

$\int_{-1}^1e^{-x}dx$

In [ ]:
def f(x):
return np.exp(-x)

f_true = np.exp(1) - 1/np.exp(1)


## Evaluating¶

$\int_{-1}^1\sqrt{|x|}dx$

In [ ]:
def g(x):
return np.sqrt(np.abs(x))

g_true = 4/3


## Make table with results¶

In [ ]:
methods = ['Trapezoid rule', "Simpson's rule", 'Gauss-Legendre']
functions = [r'$\int_{-1}^1e^{-x}dx$', r'$\int_{-1}^1\sqrt{|x|}dx$']

results = pd.concat(
[pd.DataFrame(errors, columns=methods, index=nlist) for errors in (f_error, g_error)],
keys=functions)

results


## Plot the functions¶

In [ ]:
a, b, n = -1, 1, 301
x = np.linspace(a, b, n)

fig, axs = plt.subplots(1, 2, figsize=[10,4])
axs[0].plot(x, f(x), linewidth=3)
axs[0].set(
title='$e^{-x}$',
xlim=[a,b],
ylim=[0,f(a)],
xticks=[-1,0,1],
yticks=[0])

axs[1].plot(x, g(x), linewidth=3)
axs[1].set(
title='$\sqrt{|x|}$',
xlim=[a,b],
ylim=[0,g(a)],
xticks=[-1,0,1],
yticks=[0]);


### Export figure and table¶

In [ ]:
#results.to_latex('demqua03.tex', escape=False, float_format='%.1f')
#demo.savefig([plt.gcf()], name='demqua03')