Mastering Trigonometric Functions with NumPy in Python
When working with mathematical computations in Python, NumPy is an essential library. It offers several powerful functions for performing trigonometric calculations with ease.
Basic Trigonometric Functions in NumPy
NumPy provides universal functions (ufuncs) such as sin(), cos(), and tan() which accept input in radians and return their corresponding sine, cosine, and tangent values.
Program:
Calculate the Sine of π/2
import numpy as np
x = np.sin(np.pi / 2)
print(x)
Output:
1.0
Program:
Calculate Sine Values for Multiple Angles
import numpy as np
arr = np.array([np.pi/2, np.pi/3, np.pi/4, np.pi/5])
x = np.sin(arr)
print(x)
Output:
[1. 0.8660254 0.70710678 0.58778525]
Converting Degrees to Radians
By default, trigonometric functions in NumPy expect radian inputs. But if you have angles in degrees, you can easily convert them using np.deg2rad().
Formula:
radians = degrees × (Ï€ / 180)
Program:
Convert Degrees to Radians
import numpy as np
arr = np.array([90, 180, 270, 360])
x = np.deg2rad(arr)
print(x)
Output:
[1.57079633 3.14159265 4.71238898 6.28318531]
Converting Radians to Degrees
Similarly, you can convert radian values back to degrees using np.rad2deg().
Program:
Convert Radians to Degrees
import numpy as np
arr = np.array([np.pi/2, np.pi, 1.5*np.pi, 2*np.pi])
x = np.rad2deg(arr)
print(x)
Output:
[ 90. 180. 270. 360.]
Inverse Trigonometric Functions (Finding Angles)
NumPy also provides functions for inverse trigonometric operations:
arcsin()
arccos()
arctan()
These functions return angles in radians.
Program:
Find Angle for sin⁻¹(1.0)
import numpy as np
x = np.arcsin(1.0)
print(x)
Output:
1.5707963267948966
Find Angles for Multiple Sine Values
Program:
import numpy as np
arr = np.array([1, -1, 0.1])
x = np.arcsin(arr)
print(x)
Output:
[ 1.57079633 -1.57079633 0.10016742]
Calculate Hypotenuse (Pythagorean Theorem)
Need to calculate the hypotenuse? NumPy’s hypot() function makes it simple:
Formula:
hypotenuse = √(base² + perpendicular²)
Program:
Calculate Hypotenuse for Base=3 and Perpendicular=4
import numpy as np
base = 3
perp = 4
x = np.hypot(base, perp)
print(x)
Output:
5.0