NumPy Mathematics
NumPy provides a variety of mathematical functions that operate on arrays. These functions can be broadly categorized into the following types:
Basic Mathematical Functions:
np.add(arr1, arr2)
performs element-wise addition between arraysarr1
andarr2
.np.subtract(arr1, arr2)
performs element-wise subtraction between arraysarr1
andarr2
.
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
np.add(arr1, arr2) # [5 7 9]
np.subtract(arr1, arr2) # [-3 -3 -3]
np.add(arr1, 10) # [11, 12, 13]
np.subtract(arr2, 4) # [0, 1, 2]
np.multiply(arr1, arr2)
performs element-wise multiplication between arraysarr1
andarr2
.np.divide(arr1, arr2)
performs element-wise division between arraysarr1
andarr2
.
arr1 = np.array([10, 20, 30])
arr2 = np.array([2, 4, 6])
np.multiply(arr1, arr2) # [20 80 180]
np.divide(arr1, arr2) # [ 5. 5. 5.]
np.multiply(arr1, 10). # [100, 200, 300]
np.divide(arr2, 2). # [1., 2., 3.]
np.power(arr, power)
raises elements of arrayarr
to the power ofpower
.
arr = np.array([2, 3, 4])
np.power(arr, 2) # [ 4 9 16]
np.sqrt(arr)
computes the square root of each element in arrayarr
.
arr = np.array([16, 25, 36])
np.sqrt(arr) # [4. 5. 6.]
Trigonometric Functions:
np.sin(arr)
computes the sine of each element in arrayarr
.np.cos(arr)
computes the cosine of each element in arrayarr
.np.tan(arr)
computes the tangent of each element in arrayarr
.
arr = np.array([0, np.pi/4, np.pi/2])
np.sin(arr) # [0. 0.70710678 1.]
np.cos(arr) # [1. 0.70710678 0.]
np.tan(arr) # [0. 1. 1.63312394]
Logarithmic and Exponential Functions:
np.log(arr)
calculates the natural logarithm of each element in arrayarr
.np.log10(arr)
calculates the base-10 logarithm of each element in arrayarr
.
arr = np.array([1, 10, 100])
np.log(arr) # [0. 2.30258509 4.60517019]
np.log10(arr) # [0. 1. 2.]
np.exp(arr)
calculates the exponential of each element in arrayarr
.
arr = np.array([1, 2, 3])
np.exp(arr) # [ 2.71828183 7.3890561 20.08553692]
Aggregate Functions:
np.sum(arr)
calculates the sum of all elements in arrayarr
.np.min(arr)
finds the minimum value among the elements in arrayarr
.np.max(arr)
finds the maximum value among the elements in arrayarr
.np.mean(arr)
computes the mean (average) value of elements in arrayarr
.np.median(arr)
calculates the median value of elements in arrayarr
.np.std(arr)
calculates the standard deviation of elements in arrayarr
.
arr = np.array([10, 20, 30, 40, 50])
total_sum = np.sum(arr) # 150
minimum_value = np.min(arr) # 10
maximum_value = np.max(arr) # 50
average_mean = np.mean(arr) # 30.0
middle_median = np.median(arr) # 30.0
standard_deviation = np.std(arr) # 14.14 (approximately)