Page - 16 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python
Image of the Page - 16 -
Text of the Page - 16 -
16 1 TheFirstFewSteps
real = 12.89643
integer = 42
string = ’some message’
print ’real=%.3f, integer=%d, string=%s’ % (real, integer, string)
print ’real=%9.3e, integer=%5d, string=%s’ % (real, integer, string)
Theoutput ofprint is a string, specified in termsof text and a set of variables
tobe inserted in the text. Variables are inserted in the text at places indicatedby%.
After%comesaspecificationof the formatting, e.g,%f (realnumber),%d (integer),
or%s (string). The format%9.3fmeans a real number in decimalnotation,with 3
decimals,written in afieldofwidth equal to9characters. Thevariant%.3fmeans
that thenumber iswrittenascompactlyaspossible, indecimalnotation,with three
decimals. SwitchingfwitheorE results in thescientificnotation,here1.290e+01
or1.290E+01.Writing%5dmeansthatan integer is tobewritten inafieldofwidth
equal to 5 characters. Real numbers can also be specifiedwith %g, which is used
toautomaticallychoosebetweendecimalorscientificnotation, fromwhatgives the
mostcompactoutput (typically, scientificnotation isappropriateforverysmall and
very largenumbersanddecimalnotation for the intermediate range).
A typical example of when printf formatting is required, arises when nicely
alignedcolumnsofnumbers are tobeprinted. Supposewewant to print a column
of t values together with associated function values g.t/ D t sin.t/ in a second
column.Thesimplest approachwouldbe
from math import sin
t0 = 2
dt = 0.55
# Unformatted print
t = t0 + 0*dt; g = t*sin(t)
print t, g
t = t0 + 1*dt; g = t*sin(t)
print t, g
t = t0 + 2*dt; g = t*sin(t)
print t, g
withoutput
2.0 1.81859485365
2.55 1.42209347935
3.1 0.128900053543
(Repeating the same set of statementsmultiple times, as done above, is not good
programmingpractice-oneshoulduseafor loop,asexplainedlater inSection2.3.)
Observe that the numbers in the columns are not nicely aligned. Using the printf
syntax’%6.2f %8.3f’ % (t, g) fortandg,wecancontrol thewidthof each
column and also the number of decimals, such that the numbers in a column are
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