Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Exploring the Python math Module
In this article, you’ll learn all about Python’s math module. Mathematical calculations are an essential part of most Python development. Whether you’re working on a scientific project, a financial application, or any other type of programming endeavor, you just can’t escape the need for math.
For straightforward mathematical calculations in Python, you can use the built-in mathematical operators, such as addition (+), subtraction (-), division (/), and multiplication (*). But more advanced operations, such as exponential, logarithmic, trigonometric, or power functions, are not built in. Does that mean you need to implement all of these functions from scratch?
Fortunately, no. Python provides a module specifically designed for higher-level mathematical operations: the math module.
By the end of this article, you’ll learn:
- What the Python
mathmodule is - How to use
mathmodule functions to solve real-life problems - What the constants of the
mathmodule are, including pi, tau, and Euler’s number - What the differences between built-in functions and
mathfunctions are - What the differences between
math,cmath, and NumPy are
A background in mathematics will be helpful here, but don’t worry if math isn’t your strong suit. This article will explain the basics of everything you need to know.
So let’s get started!
Free Download: Get a sample chapter from Python Tricks: The Book that shows you Python’s best practices with simple examples you can apply instantly to write more beautiful + Pythonic code.
Getting to Know the Python math Module
The Python math module is an important feature designed to deal with mathematical operations. It comes packaged with the standard Python release and has been there from the beginning. Most of the math module’s functions are thin wrappers around the C platform’s mathematical functions. Since its underlying functions are written in CPython, the math module is efficient and conforms to the C standard.
The Python math module offers you the ability to perform common and useful mathematical calculations within your application. Here are a few practical uses for the math module:
- Calculating combinations and permutations using factorials
- Calculating the height of a pole using trigonometric functions
- Calculating radioactive decay using the exponential function
- Calculating the curve of a suspension bridge using hyperbolic functions
- Solving quadratic equations
- Simulating periodic functions, such as sound and light waves, using trigonometric functions
Since the math module comes packaged with the Python release, you don’t have to install it separately. Using it is just a matter of importing the module:
>>> import math
You can import the Python math module using the above command. After importing, you can use it straightaway.