Page - 153 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 153 -
Text of the Page - 153 -
6.6 TestingCode 153
These are two equations for two unknownsC and r. We can easily eliminateC by
dividing,e.g., (6.26)by(6.27).Doingso,andproceedingtosolveforr, followedby
also introducingasubscript iβ1for r, gives
riβ1 =βln(Ei/Eiβ1)
ln(ni/niβ1) . (6.28)
The subscript is introduced, since the estimated value for r will vary with i.
Hopefully,riβ1 approaches the correct convergencerate as the number of intervals
increasesand iβq.
6.6.3 FinitePrecisionofFloating-PointNumbers
The test procedures above lead to comparison of numbers for checking that
calculations were correct. Such comparison is more complicated than what a
newcomer might think. Suppose we have a calculation a + b and want to check
that the result iswhat weexpect.
AddingIntegers We start with1+ 2:
In [1]: a = 1; b = 2; expected = 3
In [2]: a + b == expected
Out[2]: True
AddingRealNumbers Thenwe proceedwith 0.1+ 0.2:
In [3]: a = 0.1; b = 0.2; expected = 0.3
In [4]: a + b == expected
Out[4]: False
ApproximateRepresentationofRealNumbersonaComputer Sowhyis0.1+
0.2 =0.3?Thereasonis that,generally,realnumberscannotberepresentedexactly
on a computer. They must instead be approximated by a floating-point number5
that can only store a finite amount of information,usually about 17 digits of a real
number.Let usprint0.1,0.2,0.1+0.2, and0.3with17decimals:
In [5]: print(β{:.17f}\n{:.17f}\n{:.17f}\n{:.17f}β\
.format(0.1, 0.2, 0.1 + 0.2, 0.3))
0.10000000000000001
0.20000000000000001
0.30000000000000004
0.29999999999999999
We see that all of the numbers have an inaccurate digit in the 17th decimal place.
Because 0.1 + 0.2 evaluates to 0.30000000000000004 and 0.3 is represented as
0.29999999999999999, these two numbers are not equal. In general, real numbers
inPythonhave (atmost)16correctdecimals.
5https://en.wikipedia.org/wiki/Floating_point.
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