Page - 46 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 46 -
Text of the Page - 46 -
46 2 AFewMoreSteps
at thepreviouscalculation inmoredetail.Letus repeat thecalculation,but this time
printmoredecimals,
In [1]: x = 4
In [2]: y = 1.0/(x+1)
In [3]: print(βThe value of y is: {:.17f}β.format(y))
The value of y is: 0.20000000000000001
So, what should have been exactly 0.2, is really a slightly different value! The
inexact number representation gave us a small error. Usually, such errors are so
small compared to the other numbers of the calculation, that we do not need to
botherwiththem.Still,keepit inmind,sinceyouwillencounterthisissuefromtime
to time. More details regardingnumber representationson a computer are given in
Sect.6.6.3.
2.2.10 BooleanExpressions
In programming, we often need to check whether something is true or not true,
and then take action accordingly. This is handled by use of logical or boolean
expressions, which evaluate to the Boolean values true or false (i.e., not true).7 In
Python, these values are writtenTrue andFalse, respectively (note capital letters
TandF!).
The following session presents some examples of boolean expressions, while
alsoexplaining theoperators involved:
In [1]: x = 4
In [2]: # The following is a series of boolean expressions:
In [3]: x > 5 # x greater than 5
Out[3]: False
In [4]: x >= 5 # x greater than, or equal to, 5
Out[4]: False
In [5]: x < 5 # x smaller than 5
Out[5]: True
In [6]: x <= 5 # x smaller than, or equal to, 5
Out[6]: True
In [7]: x == 4 # x equal to 4
Out[7]: True
In [8]: x != 4 # x not equal to 4
Out[8]: False
Boolean values may also be combined into longer expressions by use of and and
or. Furthermore, preceding a boolean expression by not, will effectively switch
7 https://en.wikipedia.org/wiki/Boolean_data_type.
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