Page - 44 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python
Image of the Page - 44 -
Text of the Page - 44 -
44 2 BasicConstructions
# Transform y coordinates
from math import log
def f(y):
return log(y)
for i in range(len(y)):
y[i] = f(y[i])
# Write out x and y to a two-column file
filename = ’tmp_out.dat’
outfile = open(filename, ’w’) # Open file for writing
outfile.write(’# x and y coordinates\n’)
for xi, yi in zip(x, y):
outfile.write(’%10.5f %10.5f\n’ % (xi, yi))
outfile.close()
Such a file with a comment line and numbers in tabular format is very com-
mon so numpy has functionality to ease reading and writing. Here is the same
exampleusing theloadtxtandsavetxt functions innumpy for tabular data (file
file_handling_numpy.py):
filename = ’tmp.dat’
import numpy
data = numpy.loadtxt(filename, comments=’#’)
x = data[:,0]
y = data[:,1]
data[:,1] = numpy.log(y) # insert transformed y back in array
filename = ’tmp_out.dat’
filename = ’tmp_out.dat’
outfile = open(filename, ’w’) # open file for writing
outfile.write(’# x and y coordinates\n’)
numpy.savetxt(outfile, data, fmt=’%10.5f’)
2.7 Exercises
Exercise2.1:Errorswithcolon, indent, etc.
Write the program ball_function.py as given in the text and confirm that the
program runs correctly. Then save a copy of the program and use that program
during the followingerror testing.
You are supposed to introduce errors in the code, one by one. For each error
introduced, save and run the program, and comment howwell Python’s response
corresponds to the actual error. When you are finishedwith one error, re-set the
programtocorrectbehavior(andcheckthat itworks!) beforemovingonto thenext
error.
a) Change thefirst line fromdef y(t): todef y(t), i.e., removethecolon.
b) Remove the indent in front of the statementv0 = 5 inside the functiony, i.e.,
shift the text four spaces to the left.
back to the
book Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python"
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python
- Title
- Programming for Computations – Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2016
- Language
- English
- License
- CC BY-NC 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 248
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik