Page - 81 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python
Image of the Page - 81 -
Text of the Page - 81 -
3.7 DoubleandTriple Integrals 81
def test_midpoint_double():
"""Test that a linear function is integrated exactly."""
def f(x, y):
return 2*x + y
a = 0; b = 2; c = 2; d = 3
import sympy
x, y = sympy.symbols(’x y’)
I_expected = sympy.integrate(f(x, y), (x, a, b), (y, c, d))
# Test three cases: nx < ny, nx = ny, nx > ny
for nx, ny in (3, 5), (4, 4), (5, 3):
I_computed1 = midpoint_double1(f, a, b, c, d, nx, ny)
I_computed2 = midpoint_double2(f, a, b, c, d, nx, ny)
tol = 1E-14
#print I_expected, I_computed1, I_computed2
assert abs(I_computed1 - I_expected) < tol
assert abs(I_computed2 - I_expected) < tol
Lettestfunctionsspeakup?
Ifwecall theabovetest_midpoint_doublefunctionandnothinghappens,our
implementationsare correct. However, it is somewhat annoying tohave a func-
tion that is completely silentwhen itworks–arewesureall thingsareproperly
computed? During development it is therefore highly recommended to insert
a print statement such that we canmonitor the calculations and be convinced
that the test functiondoeswhatwewant. Since a test function should not have
anyprint statement,we simply comment it out aswehavedone in the function
listedabove.
The trapezoidalmethodcanbeusedasalternative for themidpointmethod.The
derivationof a formula for thedouble integral and the implementations followex-
actly the same ideas asweexplainedwith themidpointmethod,but therearemore
terms to write in the formulas. Exercise 3.13 asks you to carry out the details.
That exercise is a very good test on your understanding of themathematical and
programmingideas in thepresent section.
3.7.2 TheMidpointRuleforaTripleIntegral
Theory Once amethod thatworks for a one-dimensional problem is generalized
to twodimensions, it is usuallyquite straightforward to extend themethod to three
dimensions. Thiswillnowbedemonstratedforintegrals.Wehavethetriple integral
bZ
a dZ
c fZ
e g.x;y;z/dzdydx
back to the
book Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python"
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python
- Title
- Programming for Computations – Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2016
- Language
- English
- License
- CC BY-NC 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 248
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik