Page - 140 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 140 -
Text of the Page - 140 -
140 6 ComputingIntegralsandTestingCode
Implementation Without Function Definitions Basically, we use a for loop to
compute the sum. Each term withf(x) in the formula (6.17) is replaced by 3t2et 3
,
x by t, and h byΞt.1 A first version of this special implementation, without any
functiondefinition,could read
from math import exp
a = 0.0; b = 1.0
n = int(input(βn: β))
dt = (b - a)/n
# Integral by the trapezoidal method
v_sum = 0
for i in range(1, n, 1):
t = a + i*dt
v_sum = v_sum + 3*(t**2)*exp(t**3)
numerical = dt*(0.5*3*(a**2)*exp(a**3) +
v_sum +
0.5*3*(b**2)*exp(b**3))
exact_value = exp(1**3) - exp(0**3)
error = abs(exact_value - numerical)
rel_error = (error/exact_value)*100
print(βn={:d}: {:.16f}, error: {:g}β.format(n, numerical, error))
Theproblemwith theabovestrategy is at least three-fold:
1. To write the code, we had to reformulate (6.17) for our special problem with a
differentnotation.Errorscomeeasy then.
2. Towrite thecode,wehadtoinsert theintegrand3t2et 3
severalplacesin thecode,
whichquickly leads toerrors.
3. Ifwelaterwant tocomputeadifferentintegral, thecodemustbeeditedinseveral
places.Sucheditsare likely to introduceerrors.
Thepotentialerrorsrelated topoint2serve to illustratehowimportant it is todefine
anduse appropriatefunctions.
Implementation with Function Definitions An improved second version of the
special implementation, now with functions for the integrand v and the anti-
derivativeV,might then read
from math import exp
v = lambda t: 3*(t**2)*exp(t**3) # Define integrand
a = 0.0; b = 1.0
n = int(input(βn: β))
dt = (b - a)/n
# Integral by the trapezoidal method
1 Replacing h by Ξt is not strictly required as many use h as interval also along the time axis.
Nevertheless,Ξt is an even more popular notation for a small time interval, so we use thathere.
Programming for Computations β Python
A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
- Title
- Programming for Computations β Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Volume
- Second Edition
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2020
- Language
- English
- License
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 356
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik