Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 4af3629

Browse files
committed
Improve the rounding and summing examples.
1 parent cc32a11 commit 4af3629

1 file changed

Lines changed: 18 additions & 8 deletions

File tree

Doc/tutorial/floatingpoint.rst

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -109,14 +109,24 @@ It's important to realize that this is, in a real sense, an illusion: you're
109109
simply rounding the *display* of the true machine value.
110110

111111
One illusion may beget another. For example, since 0.1 is not exactly 1/10,
112-
summing ten values of 0.1 may not yield exactly 1.0, either::
113-
114-
>>> sum = 0.0
115-
>>> for i in range(10):
116-
... sum += 0.1
117-
...
118-
>>> sum
119-
0.9999999999999999
112+
summing three values of 0.1 may not yield exactly 0.3, either::
113+
114+
>>> .1 + .1 + .1 == .3
115+
False
116+
117+
Also, since the 0.1 cannot get any closer to the exact value of 1/10 and
118+
0.3 cannot get any closer to the exact value of 3/10, then pre-rounding with
119+
:func:`round` function cannot help::
120+
121+
>>> round(.1, 1) + round(.1, 1) + round(.1, 1) == round(.3, 1)
122+
False
123+
124+
Though the numbers cannot be made closer to their intended exact values,
125+
the :func:`round` function can be useful for post-rounding so that results
126+
have inexact values that are comparable to one another::
127+
128+
>>> round(.1 + .1 + .1, 1) == round(.3, 1)
129+
True
120130

121131
Binary floating-point arithmetic holds many surprises like this. The problem
122132
with "0.1" is explained in precise detail below, in the "Representation Error"

0 commit comments

Comments
 (0)