Chapter 15. 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
in “The math and cmath Modules”, operator
in “The operator Module”, random
in “The random Module”, fractions
in “The fractions Module”, and decimal
in “The decimal Module”. “The gmpy2 Module” also mentions the third-party module gmpy2
, which further extends Python’s numeric computation abilities. Numeric processing often requires, more specifically, the processing of arrays of numbers, covered in “Array Processing”, focusing on the standard library module array
and popular third-party extension NumPy.
The math and cmath Modules
The math
module supplies mathematical functions on floating-point numbers; the cmath
module supplies equivalent functions on complex numbers. For example, math.sqrt(-1)
raises an exception, but cmath.sqrt(-1)
returns 1j
.
Just like for any other module, the cleanest, most readable way to use these is to have, for example, import math
at the top of your code, and explicitly call, say, math.sqrt
afterward. However, if your code includes many calls to the modules’ well-known mathematical functions, it’s permissible, as an exception to the general guideline, to use at the top of your code from math import *
, and afterward just call sqrt
.
Each module exposes two float ...
Get Python in a Nutshell, 3rd 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.