The "math" Module

We have already seen using the import command for importing the matplotlib library and the numpy package. Much of Python's power rests in the vast collection of packages, libraries, and modules available for just about any application you could think of. The math module contains a host of mathematically oriented methods typical of what a programmer would need to perform basic calculations. Consider executing this set of instructions:

import math
a=math.exp(1)
print(a)
b=math.pi
print(b)
x=100
print(math.log(x,10))
print(math.log10(x))
y=math.pi/2
print(math.cos(y))
print(math.sin(y))
y=8
z=1/3
print(math.pow(y,z))

Notice once again the object-oriented dot notation for calling a method. Just about any function that can be calculated on a sophisticated calculator can be performed using the math module. For the sake of simplifying the code, if you know exactly what methods are needed from a given library, you can select a subset using the from keyword. Consider the code from earlier rewritten using the from keyword:

from math import exp, pi, log, log10, cos, sin, pow
a=exp(1)
print(a)
b=pi
print(b)
x=100
print(log(x,10))
print(log10(x))
y=pi/2
print(cos(y))
print(sin(y))
y=8
z=1/3
print(pow(y,z))

Now all the math method calls look exactly like function calls. Sometimes it is more convenient to use the reduced representation.

Last modified: Thursday, March 17, 2022, 5:00 PM