Page - 88 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python
Image of the Page - 88 -
Text of the Page - 88 -
88 3 Computing Integrals
print βExact integral:β, I_exact.evalf()
x0 = -2; x1 = 2; y0 = -2; y1 = 2
n = 1000
np.random.seed(6)
I_expected = 16.7970837117376384 # Computed with this seed
I_computed = MonteCarlo_double(
lambda x, y: np.sqrt(x**2 + y**2),
g, x0, x1, y0, y1, n)
print βMC approximation %d samples): %.16fβ % (n**2, I_computed)
assert abs(I_expected - I_computed) < 1E-15
(See thefileMC_double.py.)
3.8 Exercises
Exercise3.1:Handcalculations for the trapezoidalmethod
Compute by hand the area composed of two trapezoids (of equal width) that ap-
proximates the integral R3
1 2x3dx.Makea test functionthatcalls thetrapezoidal
function in trapezoidal.py and compares the return value with the hand-
calculatedvalue.
Filename:trapezoidal_test_func.py.
Exercise3.2:Handcalculations for themidpointmethod
Compute by hand the area composed of two rectangles (of equal width) that ap-
proximates the integral R3
1 2x3dx. Make a test function that calls the midpoint
function inmidpoint.pyand compares the return valuewith the hand-calculated
value.
Filename:midpoint_test_func.py.
Exercise3.3:Computeasimple integral
Applythetrapezoidalandmidpointfunctions tocompute the integral R6
2 x.x
1/dxwith2and100subintervals. Compute theerror too.
Filename:integrate_parabola.py.
Exercise3.4:Hand-calculationswithsine integrals
Weconsider integrating thesine function: Rb
0 sin.x/dx.
a) Let b D and use two intervals in the trapezoidal and midpoint method.
Compute the integral by hand and illustrate how the two numerical methods
approximates the integral. Comparewith theexactvalue.
b) Doa)whenbD2 .
Filename:integrate_sine.pdf.
Exercise3.5:Maketest functions for themidpointmethod
Modify thefiletest_trapezoidal.pysuch that the three tests are applied to the
functionmidpoint implementing themidpointmethodfor integration.
Filename:test_midpoint.py.
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