Login
📚 Introduction to Python Programming
Chapters ▾
⇩ Download ▾

2.6 The math module

Learning objectives

By the end of this section you should be able to

  • Distinguish between built-in functions and math functions.
  • Use functions and constants defined in the math module.

Importing modules

Python comes with an extensive standard library of modules. A module is previously written code that can be imported in a program. The import statement defines a variable for accessing code in a module. Import statements often appear at the beginning of a program.

The standard library also defines built-in functions such as print, input, and float. A built-in function is always available and does not need to be imported. The complete list of built-in functions is available in Python's official documentation.

A commonly used module in the standard library is the math module. This module defines functions such as sqrt (square root). To call sqrt, a program must import math and use the resulting math variable followed by a dot. Ex: math.sqrt(25) evaluates to 5.0.

The following program imports and uses the math module, and uses built-in functions for input and output.

Mathematical functions

Commonly used math functions and constants are shown below. The complete math module listing is available in Python's official documentation.

Table 2.3 Example constants in the math module.
ConstantValueDescription
math.ee=2.71828Euler's number: the base of the natural logarithm.
math.piπ=3.14159The ratio of the circumference to the diameter of a circle.
math.tauτ=6.28318The ratio of the circumference to the radius of a circle. Tau is equal to 2π.
Table 2.4 Example functions in the math module.
FunctionDescriptionExamples
Number-theoretic
math.ceil(x)The ceiling of x: the smallest integer greater than or equal to x.math.ceil(7.4) 8
math.ceil(-7.4) -7
math.floor(x)The floor of x: the largest integer less than or equal to x.math.floor(7.4) 7
math.floor(-7.4) -8
Power and logarithmic
math.log(x)The natural logarithm of x (to base e).math.log(math.e) 1.0
math.log(0) ValueError: math domain error
math.log(x, base)The logarithm of x to the given base.math.log(8, 2) 3.0
math.log(10000, 10) 4.0
math.pow(x, y)x raised to the power y. Unlike the ** operator, math.pow converts x and y to type float.math.pow(3, 0) 1.0
math.pow(3, 3) 27.0
math.sqrt(x)The square root of x.math.sqrt(9) 3.0
math.sqrt(-9) ValueError: math domain error
Trigonometric
math.cos(x)The cosine of x radians.math.cos(0) 1.0
math.cos(math.pi) -1.0
math.sin(x)The sine of x radians.math.sin(0) 0.0
math.sin(math.pi/2) 1.0
math.tan(x)The tangent of x radians.math.tan(0) 0.0
math.tan(math.pi/4) 0.999
(Round-off error; the result should be 1.0.)