Page - 206 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 206 -
Text of the Page - 206 -
206 8 SolvingOrdinaryDifferentialEquations
in the straight lines in between these points. Therefore, the exact solution is ready
andwe mayproceed tobringour reasoningintocode.
Implementation and Performance A simple implementation may read
(rate_piecewise_constant.py):
import numpy as np
import matplotlib.pyplot as plt
a = 0.0; b = 3.0 # time interval
N = 3 # number of time steps
dt = (b - a)/N # time step (s)
V_exact = [1.0, 2.0, 5.0, 12.0] # exact volumes (L)
V = np.zeros(4) # numerically computed volume (L)
V[0] = 1 # initial volume
r = np.zeros(3) # rates of volume increase (L/s)
r[0] = 1; r[1] = 3; r[2] = 7
for i in [0, 1, 2]:
V[i+1] = V[i] + dt*r[i]
time = [0, 1, 2, 3]
plt.plot(time, V, ’bo-’, time, V_exact, ’r’)
plt.title(’Case 1’)
plt.legend([’numerical’,’exact’], loc=’upper left’)
plt.xlabel(’t (s)’)
plt.ylabel(’V (L)’)
plt.show()
As you can see, we have included the exact (hand computed) solution in the code,
so that it gets plotted together with the numerical solution found by the program.
Thetimestepdtwillbecome1shere,andrunningthecode,producestheplot seen
in Fig. 8.1. We note that the numerical and exact solution can not be distinguished
in theplot.
Fig. 8.1 Watervolume in a tank as it develops withpiecewise constant rate of volume increase
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