Seite - 125 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
Bild der Seite - 125 -
Text der Seite - 125 -
5.7 Exercises 125
So,using the functionadd tofill thearray, takes50%longer time!
5.7 Exercises
Exercise5.1:NestedforLoopsand Lists
The code below has for loops that traverse lists of different kinds. One is with
integers, one with real numbers and one with strings. Read the code and write
down the printout you would have got if the program had been run (i.e., you are
not supposed toactually run theprogram, just read it!).
for i in [1, 2]:
# First indentation level (4 spaces)
print(’i: {:d}’.format(i))
for j in [3.0, 4.0]:
# Second indentation level (4+4 spaces)
print(’ j: {:.1f}’.format(j))
for w in [’yes’, ’no’]:
# Third indentation level (4+4+4 spaces)
print(’ w: {:s}’.format(w))
# First indentation level
for k in [5.0, 6.0]:
# Second indentation level (4+4 spaces)
print(’ k: {:.1f}’.format(k))
Filename:read_nested_for_loops.py.
Exercise5.2:ExceptionHandling:Divisions in aLoop
Write a program that N times will ask the user for two real numbers a and
b and print the result of a/b. Any exceptions should be handled properly (for
example, just give an informative printout and let the program proceed with the
next division, if any). The user should also be allowed to stop execution with
Ctrl-c.
SetN = 4 in the code (for simplicity) and demonstrate that it handles different
types of user input (i.e., floats, integers, text, just pressing enter, etc.) in a sensible
way.
Filename:compute_division.py.
Exercise5.3:TaylorSeries,sympyand Documentation
In this exercise, you are supposed to develop a Python function that approximates
sin(x)whenxisnearzero.Todothis,writeaprogramthatutilizessympy todevelop
a Taylor series for sin(x) aroundx = 0, keeping only 5 terms from the resulting
expression.Then,usesympy to turn theexpression intoa function.Let theprogram
alsoplot sin(x)and thedevelopedfunction together forx in [−π,π].
Filename:symbolic_Taylor.py.
Remarks Part of your task here, is to find andunderstand the requireddocumenta-
tion. Most likely, this means that you have to seek more information than found in
ourbook.Youmighthaveto readabout theTaylorseries (perhapsuseWikipediaor
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