How to do basic mathematical computations (in Python, using NumPy)
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 |
no | |
x-y |
no | |
x*y |
no | |
x/y |
no | |
x//y |
no | |
np.floor_divide(x,y) |
yes | |
remainder of |
x%y |
no |
remainder of |
np.remainder(x,y) |
yes |
x**y |
no | |
abs(x) |
no | |
np.abs(x) |
yes | |
np.log(x) |
yes | |
np.log(b)/np.log(a) |
yes | |
np.exp(x) |
yes | |
np.pi |
yes | |
np.sin(x) |
yes | |
np.asin(x) |
yes | |
x**0.5 |
no | |
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)