Link Search Menu Expand Document (external link)

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

See all solutions.

Task

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?

Solution

This answer assumes you have imported NumPy as follows.

1
import numpy as np
Mathematical notation Python code Requires NumPy?
x+y x+y no
xy x-y no
xy x*y no
xy x/y no
xy x//y no
xy np.floor_divide(x,y) yes
remainder of x÷y x%y no
remainder of x÷y np.remainder(x,y) yes
xy x**y no
|x| abs(x) no
|x| np.abs(x) yes
lnx np.log(x) yes
logab np.log(b)/np.log(a) yes
ex np.exp(x) yes
π np.pi yes
sinx np.sin(x) yes
sin1x np.asin(x) yes
x x**0.5 no
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.

1
2
3
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 (ncarter@bentley.edu)