Arithmetic Operations
NumPy provides element-wise arithmetic operations directly on arrays. This means that operations are applied to each element individually, resulting in a new array of the same shape.
import numpy as np
= np.array([1, 2, 3])
a = np.array([4, 5, 6])
b
= a + b # Output: array([5, 7, 9])
c
= a - b # Output: array([-3, -3, -3])
d
= a * b # Output: array([ 4, 10, 18])
e
= a / b # Output: array([0.25, 0.4 , 0.5 ])
f
= a ** 2 # Output: array([1, 4, 9]) g
Trigonometric Functions
NumPy offers a suite of trigonometric functions, including sine, cosine, tangent, and their inverses (arcsin, arccos, arctan). These functions work seamlessly with arrays.
import numpy as np
= np.array([0, np.pi/2, np.pi])
x
= np.sin(x) # Output: array([0. , 1. , 0. ])
sin_x
= np.cos(x) # Output: array([ 1.00000000e+00, 6.12323400e-17, -1.00000000e+00])
cos_x
= np.tan(x) # Output: array([ 0. , 1.63312394e+16, 0. ]) tan_x
Note the slight numerical imprecision in the cosine example; this is typical of floating-point arithmetic.
Exponential and Logarithmic Functions
NumPy provides functions for exponential and logarithmic calculations, crucial for many scientific and engineering applications.
import numpy as np
= np.array([1, 2, 3])
a
= np.exp(a) # Output: array([ 2.71828183, 7.3890561 , 20.08553692])
exp_a
= np.log(a) # Output: array([0. , 0.69314718, 1.09861229])
log_a
= np.log10(a) # Output: array([0. , 0.30103 , 0.47712125]) log10_a
Rounding Functions
NumPy offers various functions for rounding numbers to the nearest integer or to a specified number of decimal places.
import numpy as np
= np.array([1.2, 2.5, 3.8])
a
= np.round(a) # Output: array([1., 2., 4.])
rounded_a
= np.floor(a) # Output: array([1., 2., 3.])
floor_a
= np.ceil(a) # Output: array([2., 3., 4.]) ceil_a
Other Useful Functions
NumPy includes many more mathematical functions, including those for:
- Statistical calculations:
np.mean()
,np.std()
,np.median()
,np.sum()
,np.max()
,np.min()
etc. - Linear algebra:
np.dot()
,np.linalg.inv()
(matrix inverse), etc. - Special functions: Bessel functions, Gamma function, etc. (found in
scipy.special
)
These functions offer a powerful and efficient way to perform complex mathematical operations on arrays, making NumPy an indispensable tool for numerical computation in Python. Refer to the official NumPy documentation for a complete list of available functions and their detailed descriptions.