Seite - 100 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
Bild der Seite - 100 -
Text der Seite - 100 -
100 4 FunctionsandtheWritingofCode
2. Find a mathematical expression for the straight line that goes through the points
(i,yi)and (i+1,yi+1).
3. Compute they value by inserting the user’s time value in the expression for the
straight line.
a) Implement the linear interpolation technique in a function interpolate that
takesas inputanarraywith theyi measurements, the timebetweenthemΔt, and
some time t, for which the interpolated value is requested. The function should
return the interpolatedy valueat time t.
b) Write another functionfind_y that finds and prints an interpolated y value at
times requested by the user. Let find_yuse a loop in which the user is asked
for a time on the interval [0,N]. The loop can terminate when the user gives a
negative time.
c) Use the following measurements: 4.4,2.0,11.0,21.5,7.5, corresponding to
times 0,1,.. .,4 (min), and compute interpolatedvaluesat t = 2.5 and t = 3.1
min. Perform separate hand calculations to check that the output from the
programiscorrect.
Filename:linear_interpolation.py.
Exercise4.11:Test StraightLine Requirement
Assumethestraight linefunctionf(x)=4x+1.Writeascript that tests the“point-
slope” form for this line as follows. Within a chosen interval on the x-axis (for
example, forx between 0 and 10), randomlypick 100 pointson the line and check
if the followingrequirement is fulfilled foreachpoint:
f(xi)−f(c)
xi−c =a, i=1,2,.. .,100,
wherea is theslope of the lineandcdefinesa fixedpoint (c,f(c))on the line. Let
c=2here.
Filename:test_straight_line.py.
Exercise4.12:FitStraightLine toData
Assume some measurements yi,i = 1,2,.. .,5 have been collected, once every
second.Your task is to writea programthatfits a straight line to thosedata.
a) Make a function that, for given measurements and parameter values a and
b, computes the error between the straight line f(x) = ax + b and the
measurements:
e= 5∑
i=1 (axi+b−yi)2 .
b) Make a function that, in a loop, asks the user to give a and b for the line. The
corresponding value of e should then be computed and printed to screen, and a
plotof thestraight linef(x)=ax+b, togetherwith thediscretemeasurements,
shouldbeproduced.
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
- Titel
- Programming for Computations – Python
- Untertitel
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Band
- Second Edition
- Autoren
- Svein Linge
- Hans Petter Langtangen
- Verlag
- Springer Open
- Datum
- 2020
- Sprache
- englisch
- Lizenz
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Abmessungen
- 17.8 x 25.4 cm
- Seiten
- 356
- Schlagwörter
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Kategorie
- Informatik