summaryrefslogtreecommitdiffstats
path: root/Doc/tutorial
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2009-04-26 21:37:46 (GMT)
committerRaymond Hettinger <python@rcn.com>2009-04-26 21:37:46 (GMT)
commit4af362905cb1e8cb56e26a51021de855798227ea (patch)
treebc43cc23a811d729d4b51491eab69ca0cf4dc4d9 /Doc/tutorial
parentcc32a11976364cccb91cd5554c299424d4d0f92f (diff)
downloadcpython-4af362905cb1e8cb56e26a51021de855798227ea.zip
cpython-4af362905cb1e8cb56e26a51021de855798227ea.tar.gz
cpython-4af362905cb1e8cb56e26a51021de855798227ea.tar.bz2
Improve the rounding and summing examples.
Diffstat (limited to 'Doc/tutorial')
-rw-r--r--Doc/tutorial/floatingpoint.rst26
1 files changed, 18 insertions, 8 deletions
diff --git a/Doc/tutorial/floatingpoint.rst b/Doc/tutorial/floatingpoint.rst
index 78dc1d6..98e299d 100644
--- a/Doc/tutorial/floatingpoint.rst
+++ b/Doc/tutorial/floatingpoint.rst
@@ -109,14 +109,24 @@ It's important to realize that this is, in a real sense, an illusion: you're
simply rounding the *display* of the true machine value.
One illusion may beget another. For example, since 0.1 is not exactly 1/10,
-summing ten values of 0.1 may not yield exactly 1.0, either::
-
- >>> sum = 0.0
- >>> for i in range(10):
- ... sum += 0.1
- ...
- >>> sum
- 0.9999999999999999
+summing three values of 0.1 may not yield exactly 0.3, either::
+
+ >>> .1 + .1 + .1 == .3
+ False
+
+Also, since the 0.1 cannot get any closer to the exact value of 1/10 and
+0.3 cannot get any closer to the exact value of 3/10, then pre-rounding with
+:func:`round` function cannot help::
+
+ >>> round(.1, 1) + round(.1, 1) + round(.1, 1) == round(.3, 1)
+ False
+
+Though the numbers cannot be made closer to their intended exact values,
+the :func:`round` function can be useful for post-rounding so that results
+have inexact values that are comparable to one another::
+
+ >>> round(.1 + .1 + .1, 1) == round(.3, 1)
+ True
Binary floating-point arithmetic holds many surprises like this. The problem
with "0.1" is explained in precise detail below, in the "Representation Error"