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

Skip to content

Commit f94df6b

Browse files
committed
2 parents 0deb022 + 8d881fa commit f94df6b

2 files changed

Lines changed: 255 additions & 0 deletions

File tree

Lines changed: 254 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,254 @@
1+
# 15. Floating Point Arithmetic: Issues and Limitations
2+
3+
4+
5+
Floating-point numbers are represented in computer hardware as base 2 \(binary\) fractions. For example, the decimal fraction
6+
7+
```text
8+
0.125
9+
```
10+
11+
has value 1/10 + 2/100 + 5/1000, and in the same way the binary fraction
12+
13+
```text
14+
0.001
15+
```
16+
17+
has value 0/2 + 0/4 + 1/8. These two fractions have identical values, the only real difference being that the first is written in base 10 fractional notation, and the second in base 2.
18+
19+
Unfortunately, most decimal fractions cannot be represented exactly as binary fractions. A consequence is that, in general, the decimal floating-point numbers you enter are only approximated by the binary floating-point numbers actually stored in the machine.
20+
21+
The problem is easier to understand at first in base 10. Consider the fraction 1/3. You can approximate that as a base 10 fraction:
22+
23+
```text
24+
0.3
25+
```
26+
27+
or, better,
28+
29+
```text
30+
0.33
31+
```
32+
33+
or, better,
34+
35+
```text
36+
0.333
37+
```
38+
39+
and so on. No matter how many digits you’re willing to write down, the result will never be exactly 1/3, but will be an increasingly better approximation of 1/3.
40+
41+
In the same way, no matter how many base 2 digits you’re willing to use, the decimal value 0.1 cannot be represented exactly as a base 2 fraction. In base 2, 1/10 is the infinitely repeating fraction
42+
43+
```text
44+
0.0001100110011001100110011001100110011001100110011...
45+
```
46+
47+
Stop at any finite number of bits, and you get an approximation. On most machines today, floats are approximated using a binary fraction with the numerator using the first 53 bits starting with the most significant bit and with the denominator as a power of two. In the case of 1/10, the binary fraction is `3602879701896397 / 2** 55` which is close to but not exactly equal to the true value of 1/10.
48+
49+
Many users are not aware of the approximation because of the way values are displayed. Python only prints a decimal approximation to the true decimal value of the binary approximation stored by the machine. On most machines, if Python were to print the true decimal value of the binary approximation stored for 0.1, it would have to display>>>
50+
51+
```text
52+
>>> 0.1
53+
0.1000000000000000055511151231257827021181583404541015625
54+
```
55+
56+
That is more digits than most people find useful, so Python keeps the number of digits manageable by displaying a rounded value instead>>>
57+
58+
```text
59+
>>> 1 / 10
60+
0.1
61+
```
62+
63+
Just remember, even though the printed result looks like the exact value of 1/10, the actual stored value is the nearest representable binary fraction.
64+
65+
Interestingly, there are many different decimal numbers that share the same nearest approximate binary fraction. For example, the numbers `0.1` and `0.10000000000000001` and`0.1000000000000000055511151231257827021181583404541015625` are all approximated by `3602879701896397/ 2 ** 55`. Since all of these decimal values share the same approximation, any one of them could be displayed while still preserving the invariant `eval(repr(x)) == x`.
66+
67+
Historically, the Python prompt and built-in [`repr()`](https://docs.python.org/3/library/functions.html#repr) function would choose the one with 17 significant digits, `0.10000000000000001`. Starting with Python 3.1, Python \(on most systems\) is now able to choose the shortest of these and simply display `0.1`.
68+
69+
Note that this is in the very nature of binary floating-point: this is not a bug in Python, and it is not a bug in your code either. You’ll see the same kind of thing in all languages that support your hardware’s floating-point arithmetic \(although some languages may not _display_ the difference by default, or in all output modes\).
70+
71+
For more pleasant output, you may wish to use string formatting to produce a limited number of significant digits:>>>
72+
73+
```text
74+
>>> format(math.pi, '.12g') # give 12 significant digits
75+
'3.14159265359'
76+
77+
>>> format(math.pi, '.2f') # give 2 digits after the point
78+
'3.14'
79+
80+
>>> repr(math.pi)
81+
'3.141592653589793'
82+
```
83+
84+
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.
85+
86+
One illusion may beget another. For example, since 0.1 is not exactly 1/10, summing three values of 0.1 may not yield exactly 0.3, either:>>>
87+
88+
```text
89+
>>> .1 + .1 + .1 == .3
90+
False
91+
```
92+
93+
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 [`round()`](https://docs.python.org/3/library/functions.html#round) function cannot help:>>>
94+
95+
```text
96+
>>> round(.1, 1) + round(.1, 1) + round(.1, 1) == round(.3, 1)
97+
False
98+
```
99+
100+
Though the numbers cannot be made closer to their intended exact values, the [`round()`](https://docs.python.org/3/library/functions.html#round) function can be useful for post-rounding so that results with inexact values become comparable to one another:>>>
101+
102+
```text
103+
>>> round(.1 + .1 + .1, 10) == round(.3, 10)
104+
True
105+
```
106+
107+
Binary floating-point arithmetic holds many surprises like this. The problem with “0.1” is explained in precise detail below, in the “Representation Error” section. See [The Perils of Floating Point](http://www.lahey.com/float.htm) for a more complete account of other common surprises.
108+
109+
As that says near the end, “there are no easy answers.” Still, don’t be unduly wary of floating-point! The errors in Python float operations are inherited from the floating-point hardware, and on most machines are on the order of no more than 1 part in 2\*\*53 per operation. That’s more than adequate for most tasks, but you do need to keep in mind that it’s not decimal arithmetic and that every float operation can suffer a new rounding error.
110+
111+
While pathological cases do exist, for most casual use of floating-point arithmetic you’ll see the result you expect in the end if you simply round the display of your final results to the number of decimal digits you expect. [`str()`](https://docs.python.org/3/library/stdtypes.html#str)usually suffices, and for finer control see the [`str.format()`](https://docs.python.org/3/library/stdtypes.html#str.format) method’s format specifiers in [Format String Syntax](https://docs.python.org/3/library/string.html#formatstrings).
112+
113+
For use cases which require exact decimal representation, try using the [`decimal`](https://docs.python.org/3/library/decimal.html#module-decimal) module which implements decimal arithmetic suitable for accounting applications and high-precision applications.
114+
115+
Another form of exact arithmetic is supported by the [`fractions`](https://docs.python.org/3/library/fractions.html#module-fractions) module which implements arithmetic based on rational numbers \(so the numbers like 1/3 can be represented exactly\).
116+
117+
If you are a heavy user of floating point operations you should take a look at the Numerical Python package and many other packages for mathematical and statistical operations supplied by the SciPy project. See <[https://scipy.org](https://scipy.org/)>.
118+
119+
Python provides tools that may help on those rare occasions when you really _do_ want to know the exact value of a float. The [`float.as_integer_ratio()`](https://docs.python.org/3/library/stdtypes.html#float.as_integer_ratio) method expresses the value of a float as a fraction:>>>
120+
121+
```text
122+
>>> x = 3.14159
123+
>>> x.as_integer_ratio()
124+
(3537115888337719, 1125899906842624)
125+
```
126+
127+
Since the ratio is exact, it can be used to losslessly recreate the original value:>>>
128+
129+
```text
130+
>>> x == 3537115888337719 / 1125899906842624
131+
True
132+
```
133+
134+
The [`float.hex()`](https://docs.python.org/3/library/stdtypes.html#float.hex) method expresses a float in hexadecimal \(base 16\), again giving the exact value stored by your computer:>>>
135+
136+
```text
137+
>>> x.hex()
138+
'0x1.921f9f01b866ep+1'
139+
```
140+
141+
This precise hexadecimal representation can be used to reconstruct the float value exactly:>>>
142+
143+
```text
144+
>>> x == float.fromhex('0x1.921f9f01b866ep+1')
145+
True
146+
```
147+
148+
Since the representation is exact, it is useful for reliably porting values across different versions of Python \(platform independence\) and exchanging data with other languages that support the same format \(such as Java and C99\).
149+
150+
Another helpful tool is the [`math.fsum()`](https://docs.python.org/3/library/math.html#math.fsum) function which helps mitigate loss-of-precision during summation. It tracks “lost digits” as values are added onto a running total. That can make a difference in overall accuracy so that the errors do not accumulate to the point where they affect the final total:>>>
151+
152+
```text
153+
>>> sum([0.1] * 10) == 1.0
154+
False
155+
>>> math.fsum([0.1] * 10) == 1.0
156+
True
157+
```
158+
159+
### 15.1. Representation Error
160+
161+
This section explains the “0.1” example in detail, and shows how you can perform an exact analysis of cases like this yourself. Basic familiarity with binary floating-point representation is assumed.
162+
163+
_Representation error_ refers to the fact that some \(most, actually\) decimal fractions cannot be represented exactly as binary \(base 2\) fractions. This is the chief reason why Python \(or Perl, C, C++, Java, Fortran, and many others\) often won’t display the exact decimal number you expect.
164+
165+
Why is that? 1/10 is not exactly representable as a binary fraction. Almost all machines today \(November 2000\) use IEEE-754 floating point arithmetic, and almost all platforms map Python floats to IEEE-754 “double precision”. 754 doubles contain 53 bits of precision, so on input the computer strives to convert 0.1 to the closest fraction it can of the form _J_/2\*\*_N_ where _J_ is an integer containing exactly 53 bits. Rewriting
166+
167+
```text
168+
1 / 10 ~= J / (2**N)
169+
```
170+
171+
as
172+
173+
```text
174+
J ~= 2**N / 10
175+
```
176+
177+
and recalling that _J_ has exactly 53 bits \(is `>= 2**52` but `< 2**53`\), the best value for _N_ is 56:&gt;&gt;&gt;
178+
179+
```text
180+
>>> 2**52 <= 2**56 // 10 < 2**53
181+
True
182+
```
183+
184+
That is, 56 is the only value for _N_ that leaves _J_ with exactly 53 bits. The best possible value for _J_ is then that quotient rounded:&gt;&gt;&gt;
185+
186+
```text
187+
>>> q, r = divmod(2**56, 10)
188+
>>> r
189+
6
190+
```
191+
192+
Since the remainder is more than half of 10, the best approximation is obtained by rounding up:&gt;&gt;&gt;
193+
194+
```text
195+
>>> q+1
196+
7205759403792794
197+
```
198+
199+
Therefore the best possible approximation to 1/10 in 754 double precision is:
200+
201+
```text
202+
7205759403792794 / 2 ** 56
203+
```
204+
205+
Dividing both the numerator and denominator by two reduces the fraction to:
206+
207+
```text
208+
3602879701896397 / 2 ** 55
209+
```
210+
211+
Note that since we rounded up, this is actually a little bit larger than 1/10; if we had not rounded up, the quotient would have been a little bit smaller than 1/10. But in no case can it be _exactly_ 1/10!
212+
213+
So the computer never “sees” 1/10: what it sees is the exact fraction given above, the best 754 double approximation it can get:&gt;&gt;&gt;
214+
215+
```text
216+
>>> 0.1 * 2 ** 55
217+
3602879701896397.0
218+
```
219+
220+
If we multiply that fraction by 10\*\*55, we can see the value out to 55 decimal digits:&gt;&gt;&gt;
221+
222+
```text
223+
>>> 3602879701896397 * 10 ** 55 // 2 ** 55
224+
1000000000000000055511151231257827021181583404541015625
225+
```
226+
227+
meaning that the exact number stored in the computer is equal to the decimal value 0.1000000000000000055511151231257827021181583404541015625. Instead of displaying the full decimal value, many languages \(including older versions of Python\), round the result to 17 significant digits:&gt;&gt;&gt;
228+
229+
```text
230+
>>> format(0.1, '.17f')
231+
'0.10000000000000001'
232+
```
233+
234+
The [`fractions`](https://docs.python.org/3/library/fractions.html#module-fractions) and [`decimal`](https://docs.python.org/3/library/decimal.html#module-decimal) modules make these calculations easy:&gt;&gt;&gt;
235+
236+
```text
237+
>>> from decimal import Decimal
238+
>>> from fractions import Fraction
239+
240+
>>> Fraction.from_float(0.1)
241+
Fraction(3602879701896397, 36028797018963968)
242+
243+
>>> (0.1).as_integer_ratio()
244+
(3602879701896397, 36028797018963968)
245+
246+
>>> Decimal.from_float(0.1)
247+
Decimal('0.1000000000000000055511151231257827021181583404541015625')
248+
249+
>>> format(Decimal.from_float(0.1), '.17')
250+
'0.10000000000000001'
251+
```
252+
253+
####
254+

SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,5 @@
1515
* [11. Brief Tour of the Standard Library — Part II](11.-brief-tour-of-the-standard-library-part-ii.md)
1616
* [12. Virtual Environments and Packages](12.-virtual-environments-and-packages.md)
1717
* [13. What Now?](13.-what-now.md)
18+
* [15. Floating Point Arithmetic: Issues and Limitations](15.-floating-point-arithmetic-issues-and-limitations.md)
1819

0 commit comments

Comments
 (0)