NumPy is a fundamental package for scientific computing in Python. It provides support for large, multi-dimensional arrays and matrices, along with a vast collection of high-level mathematical functions to operate on these arrays. NumPy is widely used for data science, machine learning, and other technical computing applications.
In this comprehensive guide, we will explore some of the most essential mathematical functions for numerical programming in NumPy, focusing on arithmetic, trigonometric, and exponential functions. We will learn how to leverage these functions to perform mathematical operations on NumPy arrays efficiently.
Table of Contents
Open Table of Contents
Overview of Key Mathematical Functions in NumPy
NumPy provides a wide variety of mathematical functions under the numpy
module. The key categories include:
-
Arithmetic functions - Simple mathematical operations like
add()
,subtract()
,multiply()
anddivide()
. -
Trigonometric functions - Functions for calculating trigonometric ratios and inverse ratios like
sin()
,cos()
,tan()
etc. -
Exponential and logarithmic functions - Exponential functions like
exp()
,expm1()
,exp2()
and logarithmic functions likelog()
,log10()
,log2()
etc. -
Power and root functions - Power functions like
power()
,sqrt()
,cbrt()
for calculating roots etc. -
Rounding functions - Functions for rounding numbers to specific decimal places like
around()
,floor()
,ceil()
etc. -
Statistical functions - Broad category of statistical functions like
mean()
,median()
,corrcoef()
etc.
In this guide, we will specifically focus on the usage and examples of key arithmetic, trigonometric and exponential functions.
Arithmetic Functions
Arithmetic functions allow us to perform simple mathematical operations on arrays element-wise. This includes addition, subtraction, multiplication, division etc.
Some of the commonly used arithmetic functions are:
-
numpy.add(x1, x2)
- Adds arguments element-wise. -
numpy.subtract(x1, x2)
- Subtracts arguments element-wise. -
numpy.multiply(x1, x2)
- Multiplies arguments element-wise. -
numpy.divide(x1, x2)
- Divides arguments element-wise. -
numpy.reciprocal(x)
- Return the reciprocal of the argument, element-wise. Calculates 1/x. -
numpy.power(x1, x2)
- First array elements raised to powers from second array, element-wise. -
numpy.mod(x1, x2)
- Returns element-wise remainder of division.
Let’s take a look at some examples:
import numpy as np
a = np.array([1, 2, 3])
b = np.array([3, 2, 1])
c = np.add(a, b)
print(c)
# Output: [4 4 4]
d = np.subtract(a, b)
print(d)
# Output: [-2 0 2]
e = np.multiply(a, b)
print(e)
# Output: [3 4 3]
f = np.divide(a, b)
print(f)
# Output: [0.33333333 1. 3. ]
We can perform these operations between scalars and arrays too:
g = np.multiply(a, 2)
print(g)
# Output: [2 4 6]
h = np.power(a, 2)
print(h)
# Output: [1 4 9]
One important distinction is that unlike simple math operators like +
, -
, *
, /
, the NumPy arithmetic functions will not broadcast singleton dimensions during array operations. The array shapes must match exactly or an exception will be raised.
# Broadcasting works
c = a + 2
# Output: [3 4 5]
# Raises error
c = np.add(a, 2)
# ValueError: operands could not be broadcast together
Trigonometric Functions
NumPy provides common trigonometric functions that operate on arrays element-wise. These include:
numpy.sin(x)
- Sine of x radiannumpy.cos(x)
- Cosine of x radiannumpy.tan(x)
- Tangent of x radiannumpy.arcsin(x)
- Inverse sine of x in radiansnumpy.arccos(x)
- Inverse cosine of x in radiansnumpy.arctan(x)
- Inverse tangent of x in radiansnumpy.hypot(x1, x2)
- Returns hypotenuse of right angle trianglenumpy.deg2rad(x)
- Convert angles from degrees to radiansnumpy.rad2deg(x)
- Convert angles from radians to degrees
Trigonometric functions accept input arrays in radians and return output arrays with values between -1
and 1
or -π
and π
.
Here are some usage examples:
import numpy as np
a = np.array([0, 30, 45, 60, 90])
print(np.sin(a * np.pi/180))
# [0. 0.5 0.70710678 0.8660254 1. ]
print(np.cos(a * np.pi/180))
# [ 1.00000000 0.86602540 0.70710678 0.50000000 6.12303177e-17]
print(np.tan(a * np.pi/180))
# [0. 0.57735027 1. 1.73205081 1.63312394e+16]
print(np.arcsin(a/100) * 180 / np.pi)
# [ 0. 30.45733257 44.99703193 59.99481048 89.99955736]
We can also use hypot()
to find the length of the hypotenuse:
print(np.hypot(3, 4)) # 5.0
print(np.hypot(6, 8)) # 10.0
And convert between degrees and radians:
print(np.deg2rad(90)) # 1.5707963267948966 rad
print(np.rad2deg(np.pi/2)) # 90.0 deg
Exponential and Logarithmic Functions
NumPy provides common exponential and logarithmic functions that also apply element-wise on arrays.
Some useful exponential functions are:
numpy.exp(x)
- Exponential of xnumpy.expm1(x)
- Exponential of x - 1numpy.exp2(x)
- 2 raised to the power x
Logarithmic functions include:
numpy.log(x)
- Natural logarithm of xnumpy.log10(x)
- Base 10 logarithm of xnumpy.log2(x)
- Base 2 logarithm of xnumpy.log1p(x)
- Natural logarithm of 1 + x
Let’s look at some examples:
import numpy as np
a = np.array([1, 2, 3])
print(np.exp(a))
# [ 2.71828183 7.3890561 20.08553692]
print(np.expm1(a))
# [ 1.71828183 6.3890561 19.08553692]
print(np.log(a))
# [0. 0.69314718 1.09861229]
print(np.log10(a))
# [0. 0.30103 0.47712125]
print(np.log2(a))
# [0. 1. 1.5849625 ]
We can calculate the natural exponential base e
raised to different powers:
print(np.exp2(2)) # 4.0
print(np.exp2(3)) # 8.0
And vice versa for logarithms:
print(np.log2(4)) # 2.0
print(np.log2(8)) # 3.0
These exponential and logarithmic functions are useful for scientific and mathematical applications where we need to analyze growth rates, interest rates or run complex calculations.
Practical Examples and Uses
Let’s look at some practical examples of how these arithmetic, trigonometric and exponential functions can be used:
Statistical calculations
We can calculate statistical properties like mean, variance, standard deviation on array data using NumPy functions:
import numpy as np
data = np.array([1.1, 2.2, 3.3, 4.4, 5.5])
mean = np.mean(data)
var = np.var(data)
std = np.std(data)
print(mean, var, std)
# 3.3 2.25 1.5
Fourier transforms
NumPy provides fft
module to calculate discrete Fourier transforms. We can use trigonometric functions for signal processing:
import numpy as np
time_step = 0.02
period = 5
time_vec = np.arange(0, 20, time_step)
sig = np.sin(2 * np.pi / period * time_vec)
Fourier = np.fft.rfft(sig)
Curve fitting
We can fit curves and interpolate data points using polynomial functions:
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.array([1, 4, 9, 16, 25])
poly = np.polyfit(x, y, 2)
print(poly)
# [ 1.00000000e+00 0.00000000e+00 1.00000000e+00]
Numpy ufuncs
User-defined functions can be applied on NumPy arrays using numpy.frompyfunc()
. We can build customized ufuncs using arithmetic operations:
import numpy as np
def exponential(x, exponent):
return np.power(x, exponent)
vectorized_exp = np.frompyfunc(exponential, 2, 1)
print(vectorized_exp([1, 2, 3], 2))
# [1 4 9]
Conclusion
In this comprehensive guide, we explored some of the most important arithmetic, trigonometric and exponential functions provided by NumPy. These functions allow us to apply mathematical operations on NumPy arrays element-wise.
We looked at various examples of how these functions work and how to use them for statistical calculations, Fourier transforms, curve fitting, and building vectorized ufuncs in NumPy.
NumPy’s mathematical functions are optimized to work with NumPy’s multi-dimensional arrays for scientific computing. Leveraging these functions can help us write efficient numerical code in Python.
There are many more mathematical and statistical functions like rounding, set operations, random sampling etc. that NumPy supports. Be sure to refer to the official NumPy documentation and tutorials for more information.