DataScience Workbook / 05: Introduction to Programming / 3. Introduction to Python programming / 3.3. Math module - various mathematical functions

Before starting this tutorial, there are a few requirements that you should have in place.

  • Firstly, you should be familiar with using the command line in terminal on your computer.
    …from the practical tutorials in section

  • Secondly, you should have Python installed on your local machine.
    …from the practical tutorial

  • Thirdly, you should have a Python Integrated Development Environment (IDE) set up on your computer, e.g., PyCharm or JupyterLab or any text editor.
    …from the practical tutorial

  • Finally, you should have a basic understanding of Python programming.
    …from the practical tutorial

Math in Python

Mathematics is a fundamental aspect of programming, and Python provides a range of tools and resources for working with math. Python provides a robust set of tools for working with math, including:

  • built-in operators, for example: +, -, *, /, %, //, **
  • built-in functions, for example: sum(), min(), max(), round()
  • built-in modules like math, and
  • the ability to import external libraries for more specialized tasks, for example: NumPy, SciPy, and Pandas

The math module is a built-in module in Python that provides access to many mathematical functions. It includes functions that provide more advanced mathematical operations such as:

trigonometric logarithmic exponential statistical

In addition to built-in modules, Python also provides a way to import external libraries, such as NumPy, SciPy, and Pandas. These libraries contain a range of specialized functions and tools for working with specific areas of mathematics and data analysis.

When use math module?

Using the math module in Python can help you perform complex mathematical operations with ease. This module is commonly used in scientific and mathematical computations and can be a useful tool for data analysts, engineers, and scientists who work with numerical data. In this module, you can perform various mathematical operations, such as finding the square root of a number, finding the value of a mathematical constant such as pi, and much more.

Getting Started

You can try out the math module on your local machine if you have Python installed.

If you want to make up for the installation step, you can follow the installation guide provided in the tutorial .

Alternatively, if you prefer to work online, you can use various online Python interpreters such as Repl.it ⤴, PythonAnywhere ⤴, or Colab ⤴. These online interpreters provide a Python shell and allow you to run Python code without installing Python on your local machine.

For example, you can use online Python shell immediately available at https://www.python.org/shell/ ⤴ to experiment with the math module.
Simply type in your Python code in the shell and hit enter to see the output.

03_python-online-console.png

Built-in Operators

Python has several built-in operators for basic arithmetic operations, such as:

operator function description
+ addition  
- subtraction  
* multiplication  
/ division  

In addition, Python also provides operators for more advanced mathematical operations, such as:

% modulus for finding the remainder of a division
// integer division for performing integer division
** exponentiation for raising a number to a power

BASIC ARITHMETICS

x = 10
y = 3

# Addition
z = x + y
print(z)                        # Output: 13

# Subtraction
z = x - y
print(z)                        # Output: 7

# Multiplication
z = x * y
print(z)                        # Output: 30

# Division
z = x / y
print(z)                        # Output: 3.3333333333333335

ADVANCED OPERATIONS

Exponentiation

Python has an exponentiation operator ** that raises a number to a power.

x = 2
y = 3

# Exponentiation
z = x ** y
print(z)                        # Output: 8

Integer Division

In Python, integer division is performed using the double slash // operator

x = 23
y = 5

# Integer division
z = x // y
print(z)                        # Output: 4

Modulus

In Python, the modulus operation is performed using the percent % operator.

x = 23
y = 5

# Modulus operation
z = x % y
print(z)                        # Output: 3

Built-in Functions

Python also has many built-in functions for performing mathematical operations.

function example description
abs(x) abs(-10)
returns: 10
returns the absolute value of a number
round(x, y) round(3.14159, 2)
returns: 3.14
rounds a number (x) to a specified number (y) of decimal places
sum(list) sum([1,2,3])
returns: 6
return the sum of the values in a list
min(list) min([1,2,3])
returns: 1
return the minimum value in a list
max(list) max([1,2,3])
returns: 3
return the maximum value in a list

The math module provides a range of additional mathematical functions, including trigonometric functions, logarithmic functions, statistical & special functions, and more.

Built-in Module: math

MATH is a built-in module (no installation required) that contains various mathematical constants and more advanced mathematical operations such as trigonometric functions, logarithmic functions, and statistical functions, among others.

The math module does not contain functions for basic arithmetic operations such as addition, subtraction, multiplication, and division. These are basic mathematical operations that can be performed using the standard arithmetic operators in Python, such as +, -, *, /.

CheatSheet: math

In the tabs below you can find the corresponding tables with math module functions along with function description and usage examples.

Basic operations:
FunctionExampleDescription
math.sqrt(x)math.sqrt(25)
returns: 5
Returns the square root of x.
math.factorial(x)math.factorial(5)
returns: 120
Returns the factorial of x.
math.ceil(x)math.ceil(2.7)
returns: 3
Rounds up a number to the nearest integer.
math.floor(x)math.floor(2.7)
returns: 2
Rounds down a number to the nearest integer.
math.trunc(x)math.trunc(3.5)
returns: 3
Returns the integer value of x (truncates towards zero).
math.abs(x)math.abs(-10)
returns: 10
Returns the absolute value of provided number in the same type.
math.fabs(x)math.fabs(-10)
returns: 10.0
Returns the absolute value of provided number as a float-point number.
math.log(x)math.log(10)
returns: 2.30258509
Returns the natural logarithm (base e) of x.
math.log10(x)math.log10(100)
returns: 2.0
Returns the base-10 logarithm of x.
math.exp(x)math.exp(2)
returns: 7.3890560
Returns the exponential value of x.
math.pow(x, y)math.pow(2, 3)
returns: 8
Returns the value of x raised to the power of y.
math.copysign(x, y)math.copysign(10, -1)
returns: -10.0
Returns a value with the magnitude of x and the sign of y.
math.fmod(x, y)math.fmod(10, 3)
returns: 1.0
Returns the remainder of x/y as a float.
math.gcd(x, y)math.gcd(24, 36)
returns: 12
Returns the greatest common divisor of x and y.
math.hypot(x, y)math.hypot(3, 4)
returns: 5.0
Returns the Euclidean norm, sqrt(x2 + y2).
Constants:
FunctionExampleDescription
math.emath.eA mathematical constant that represents the value of e.
math.infmath.infRepresents positive infinity, which is a value greater than any finite number.
math.nanmath.nanRepresents a value that is not a number (NaN).
math.pimath.piA mathematical constant that represents the value of pi.
math.taumath.tauRepresents the mathematical constant tau, which is equal to 2*pi.
Trigonometry:
FunctionExampleDescription
math.sin(x)math.sin(math.pi/2)Returns the sine of an angle in radians.
math.cos(x)math.cos(math.pi)Returns the cosine of an angle in radians.
math.tan(x)math.tan(math.pi/4)Returns the tangent of an angle in radians.
math.radians(x)math.radians(180)
returns: 3.14159265
Converts an angle from degrees to radians.
math.degrees(x)math.degrees(math.pi)
returns: 180.0
Converts an angle from radians to degrees.
math.asin(x)math.asin(0.5)
returns: 0.5235987
Returns the arc sine (in radians) of x.
math.acos(x)math.acos(0.5)
returns: 1.0471975
Returns the arc cosine (in radians) of x.
math.atan(x)math.atan(1)
returns: 0.7853981
Returns the arc tangent (in radians) of x.
math.atan2(y, x)math.atan2(1, 1)
returns: 0.7853981
Returns the arc tangent (in radians) of y/x, in the range [-pi, pi].
Logic:
FunctionExampleDescription
math.isnan(x)math.isnan(10)
returns: False
Returns True if x is NaN (not a number), False otherwise.
math.isinf(x)math.isinf(10)
returns: False
Returns True if x is positive or negative infinity, and False otherwise.
math.isfinite(x)math.isfinite(10)
returns: True
Returns True if x is a finite number (i.e., not infinity or NaN), and False otherwise.
math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)math.isclose(3.5, 3.6, rel_tol=0.1)
returns: True
Returns True if a is close in value to b, False otherwise.

Import MATH module

The math module is built into Python and does NOT require any installation.

To use the math module, you need to import it first using the import statement:

import math

Once the math module is imported, you can access all its functions by prefixing them with math, followed by a dot and the function name, math.function_name().
For example, to find the square root of a number, you can use a math.sqrt() function:

my_variable = math.sqrt(5)