Seite - 85 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
Bild der Seite - 85 -
Text der Seite - 85 -
4.1 Functions:HowtoWriteThem? 85
andtest it!).This isbecausePythonreadsthe listedargumentsfromleft to right,and
does not know that an argument is taken out of the list before it comes to the end
(but then it is too late).
4.1.6 AFunctionwithTwoReturnValues
Takeaslightvariationofourcasewith theball, assuming that theball isnot thrown
straightup,butatanangle,so that twocoordinatesareneededtospecify itsposition
atany time.
According to Newton’s laws (when air resistance is negligible), the vertical
position is given by y(t) = v0yt − 0.5gt2 and, simultaneously, the horizontal
positionbyx(t)=v0xt. We can includeboth these expressions in a new versionof
ourprogramthatfinds thepositionof theball at a given time:
def xy(v0x, v0y, t):
"""Compute horizontal and vertical positions at time t"""
g = 9.81 # acceleration of gravity
return v0x*t, v0y*t - 0.5*g*t**2
v_init_x = 2.0 # initial velocity in x
v_init_y = 5.0 # initial velocity in y
time = 0.6 # chosen point in time
x, y = xy(v_init_x, v_init_y, time)
print(’Horizontal position: {:g} , Vertical position: {:g}’.format(x, y))
We note that in the returnstatement, the returnedvalues (twohere)areseparated
by a comma. Here, the x coordinate will be computed by v0x*t, while the y
coordinate will be computed like before. These two calculations produce two
numbers that are returned to variablesx andy in main. Note that, the order of the
resultsreturnedfromthefunctionmustbethesameastheorderofthecorresponding
variables in the assignment statement. Note the use of a comma both in the return
statementand theassignment statement.
4.1.7 CallingaFunctionDefinedwithKeywordParameters
Let us adjust the previousprogramslightly, introducingkeywordparameters in the
definition. For example, if we use 0.6 as a default value fort, and aim to get the
sameprintoutasbefore, theprogramreads
def xy(v0x, v0y, t=0.6):
"""Compute horizontal and vertical positions at time t"""
g = 9.81 # acceleration of gravity
return v0x*t, v0y*t - 0.5*g*t**2
v_init_x = 2.0 # initial velocity in x
v_init_y = 5.0 # initial velocity in y
x, y = xy(v_init_x, v_init_y)
print(’Horizontal position: {:g} , Vertical position: {:g}’.format(x, y))
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