Page - 35 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 35 -
Text of the Page - 35 -
1.8 ConcludingRemarks 35
messages. This also goes for lower and upper case letters. If you (after importing
from math) give the command pi, you get 3.1415 . . .. However, if you write Pi,
you get an error message. Pay attention to such details also when they are given in
later chapters.
1.8.2 WriteReadableCode
When you write a computer program, you have two very different kinds of
readers. One is Python, which will interpret and run your program according to
the rules. The other is some human, for example, yourself or a peer. It is very
important to organize and comment the code so that you can go back to your
own code after, e.g., a year and still understand what clever constructions you
put in there. This is relevant when you need to change or extend your code
(which usually happens often in reality). Organized coding and good commenting
is even more critical if other peopleare supposed to understandcode that you have
written.
It mightbe instructive to see an exampleof code that is not very readable. If we
useourveryfirstproblem, i.e. computingtheheighty ofaball thrownupin theair,
themathematical formulationreads:
y=v0tβ0.5gt2.
Now,insteadofourpreviousprogramball.py,wecouldwriteaworkingprogram
(inbad style!) like:
# This is an example of bad style!
m=5;u=9.81;y=0.6
t=m*y-u*0.5*y**2;print(t)
Running this code, would give the correct answer printed out. However, upon
comparison with the mathematical writing, it is not even clear that the two are
related,unlessyousit downand lookcarefullyat it!
In this code,
β’ variablenamesdonotcorrespondto the mathematicalvariables
β’ thereareno(explaining)comments
β’ noblank lines
β’ nospace toeachsideof=and-
β’ several statementsappearon the same linewith nospace inbetween
When comparing this βbad styleβ code to the original code in ball.py, the point
shouldbeclear.
1.8.3 FastCodeorSlowerandReadableCode?
Innumericalcomputing, there isa strongtraditionforpayingmuchattention to fast
code. Industrialapplicationsofnumericalcomputingoften involvesimulations that
Programming for Computations β Python
A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
- Title
- Programming for Computations β Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Volume
- Second Edition
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2020
- Language
- English
- License
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 356
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik