Chapter 16. Numeric Processing
You can perform some numeric computations with operators (covered in “Numeric Operations”) and built-in functions (covered in “Built-in Functions”). Python also provides modules that support additional numeric computations, covered in this chapter: math and cmath, statistics, operator, random and secrets, fractions, and decimal. Numeric processing often requires, more specifically, the processing of arrays of numbers; this topic is covered in “Array Processing”, focusing on the standard library module array and popular third-party extension NumPy. Finally, “Additional numeric packages” lists several additional numeric processing packages produced by the Python community. Most examples in this chapter assume you’ve imported the appropriate module; import statements are only included where the situation might be unclear.
Floating-Point Values
Python represents real numeric values (that is, those that are not integers) using variables of type float. Unlike integers, computers can rarely represent floats exactly, due to their internal implementation as a fixed-size binary integer significand (often incorrectly called “mantissa”) and a fixed-size binary integer exponent. floats have several limitations (some of which can lead to unexpected results).
For most everyday applications, floats are sufficient for arithmetic, but they are limited in the number of decimal places they can represent:
>>
>
f
=
1.1
+
2.2
-
3.3
# f should be equal to 0
>>
>
f
4.440892098500626e-16 ...
Get Python in a Nutshell, 4th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.