Page - 295 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 295 -
Text of the Page - 295 -
9.2 FiniteDifferenceMethods 295
Problemswith reusing therhs function
Therhs functionmust takeuandtasarguments,because that is requiredby
theode_FE function. What about the variablesbeta,dx,L,x,dsdt,g, and
dudx that therhs function needs? These are global in the solution we have
presented so far. Unfortunately, this has an undesired side effect: we cannot
import therhs function in a new file, definedudx anddsdt in this new file
and get the importedrhs to use these functions. The importedrhswill use
theglobalvariables, includingfunctions, in itsownmodule.
Howcanwefindsolutions to thisproblem?Technically,wemustpack the
extra data beta, dx, L, x, dsdt, g, and dudxwith the rhs function, which
requires more advanced programming considered beyond the scope of this
text.
A class is the simplest construction for packing a function together with
data, see the beginning of Chapter 7 in [11] for a detailed example on how
classes can be used in such a context. Another solution in Python, and
especially in computer languages supporting functional programming, is so
calledclosures.TheyarealsocoveredinChapter7 inthementionedreference
and behave in a magic way. The third solution is to allow an arbitrary set of
arguments forrhs in a list to be transferred toode_FEand then back torhs.
AppendixH.4 in [11]explains the technicaldetails.
9.2.4 Animation:HeatConductioninaRod
Let us return to the case with heat conduction in a rod (9.1)–(9.4). Assume that
the rod is 50cm long and made of aluminum alloy 6082. Theβ parameter equals
κ/( c), where κ is the heat conduction coefficient, is the density, and c is the
heat capacity. We can find proper values for these physical quantities in the case
of aluminum alloy 6082: = 2.7 · 103 kg/m3, κ = 200 WmK, c = 900 JKkg.
This results in β = κ/( c) = 8.2 · 10−5 m2/s. Preliminary simulations show
that we are close to a constant steady state temperature after 1h, i.e., T =
3600s.
Therhs function from the previoussection can be reused, only the functionss,
dsdt,g, anddudxmust bechanged(seefilerod_FE.py):
def dudx(t):
return 0
def s(t):
return 323
def dsdt(t):
return 0
def g(x, t):
return 0
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