Link Search Menu Expand Document (external link)

How to do basic mathematical computations (in Python, using NumPy)

See all solutions.


How do we write the most common mathematical operations in a given piece of software? For example, how do we write multiplication, or exponentiation, or logarithms, in Python vs. R vs. Excel, and so on?


This answer assumes you have imported NumPy as follows.

import numpy as np
Mathematical notation Python code Requires NumPy?
$x+y$ x+y no
$x-y$ x-y no
$xy$ x*y no
$\frac xy$ x/y no
$\left\lfloor\frac xy\right\rfloor$ x//y no
$\left\lfloor\frac xy\right\rfloor$ np.floor_divide(x,y) yes
remainder of $x\div y$ x%y no
remainder of $x\div y$ np.remainder(x,y) yes
$x^y$ x**y no
$\vert x\vert$ abs(x) no
$\vert x\vert$ np.abs(x) yes
$\ln x$ np.log(x) yes
$\log_a b$ np.log(b)/np.log(a) yes
$e^x$ np.exp(x) yes
$\pi$ np.pi yes
$\sin x$ np.sin(x) yes
$\sin^{-1} x$ np.asin(x) yes
$\sqrt x$ x**0.5 no
$\sqrt x$ np.sqrt(x) yes

Other trigonometric functions are also available besides just np.sin, including np.cos, np.tan, etc.

NumPy automatically applies any of these functions to all entries of a NumPy array or pandas Series, but the built-in Python functions do not have this feature. For example, to square all numbers in an array, see below.

import numpy as np
example_array = np.array( [ -3, 2, 0.5, -1, 10, 9.2, -3.3 ] )
example_array ** 2
array([  9.  ,   4.  ,   0.25,   1.  , 100.  ,  84.64,  10.89])

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Contributed by Nathan Carter (