300 Introduction to Computational Models with Python
5 # It start with a small number of trapezoids and
6 # increasing
7 # J M Garrido. Updated in Python Sep 28, 2014
8 import numpy as np
9 def myf (x):
10 return np.exp (x)
11
12 n = 4 # initial number of trapezoids
13 xa = 0.0 # lower bound interval of x
14 xb = 1.0 # upper bound
15 exactint = 1.718282 # exact value of integral
16 print "Compute the integral of f(x) = e^x "
17 print "Exact value of integral: ", exactint
18 while n <= 16500:
19 x = np.linspace(xa, xb, n)
20 y = myf(x)
21 intv = np.trapz(y, x) # compute integral
22 errint = intv - exactint
23 print "n=", n, " integral =", intv, " error =", errint
24 n = n * 2
The following listing shows the execution of the Python interpreter and
running of