NumPy ufunc Trigonometric Functions in Python

Last updated 3 weeks, 4 days ago | 96 views 75     5

Tags:- Python NumPy

Trigonometry is essential in fields like geometry, physics, signal processing, and engineering. NumPy, with its fast and vectorized universal functions (ufuncs), provides a comprehensive set of trigonometric operations for handling angles, waveforms, and periodic data efficiently.

This article dives deep into the trigonometric ufuncs in NumPy, covering all standard and inverse functions, degree-radian conversions, hyperbolic versions, and real-world examples.


What Are Trigonometric Functions?

The core trigonometric functions include:

  • Sine (sin)

  • Cosine (cos)

  • Tangent (tan)

And their inverse counterparts:

  • Arcsine (arcsin)

  • Arccosine (arccos)

  • Arctangent (arctan, arctan2)


NumPy Trigonometric Function List

✅ Basic Functions (Input in radians):

Function Description
np.sin(x) Sine of angle x
np.cos(x) Cosine of angle x
np.tan(x) Tangent of angle x

Inverse Trigonometric:

Function Description
np.arcsin(x) Inverse sine (returns radians)
np.arccos(x) Inverse cosine (returns radians)
np.arctan(x) Inverse tangent (returns radians)
np.arctan2(y, x) Arctangent of y/x, considers quadrant

Angle Conversion:

Function Description
np.deg2rad(x) Convert degrees to radians
np.rad2deg(x) Convert radians to degrees

Hyperbolic Trigonometry:

Function Description
np.sinh(x) Hyperbolic sine
np.cosh(x) Hyperbolic cosine
np.tanh(x) Hyperbolic tangent
np.arcsinh(x) Inverse hyperbolic sine
np.arccosh(x) Inverse hyperbolic cosine
np.arctanh(x) Inverse hyperbolic tangent

Step-by-Step Examples


1. Basic Trigonometric Functions

import numpy as np

angles = np.array([0, np.pi/2, np.pi, 3*np.pi/2])
print("sin:", np.sin(angles))
print("cos:", np.cos(angles))
print("tan:", np.tan(angles))

✅ Output:

sin: [ 0.  1.  0. -1.]
cos: [ 1.  0. -1.  0.]
tan: [ 0. inf  0. inf]  # inf due to division by zero in tan

2. Inverse Trigonometric Functions

x = np.array([0, 0.5, 1.0])
print("arcsin:", np.arcsin(x))
print("arccos:", np.arccos(x))
print("arctan:", np.arctan(x))

✅ Output:

arcsin: [0.         0.52359878 1.57079633]
arccos: [1.57079633 1.04719755 0.        ]
arctan: [0.         0.46364761 0.78539816]

3. Converting Between Degrees and Radians

degrees = np.array([0, 30, 90, 180])
radians = np.deg2rad(degrees)
print("Radians:", radians)

back_to_degrees = np.rad2deg(radians)
print("Degrees:", back_to_degrees)

4. Plotting a Sine Wave (Optional Visual Example)

import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)

plt.plot(x, y)
plt.title("Sine Wave")
plt.xlabel("Angle (radians)")
plt.ylabel("sin(x)")
plt.grid(True)
plt.show()

5. Using arctan2 for 2D Vector Angles

y = np.array([1, -1])
x = np.array([1, -1])
angles = np.arctan2(y, x)
print("Vector angles (radians):", angles)
print("Vector angles (degrees):", np.rad2deg(angles))

Hyperbolic Functions

x = np.array([0, 1, 2])

print("sinh:", np.sinh(x))
print("cosh:", np.cosh(x))
print("tanh:", np.tanh(x))

✅ Full Example

import numpy as np

# Define angles in degrees and convert to radians
angles_deg = np.array([0, 30, 45, 60, 90])
angles_rad = np.deg2rad(angles_deg)

# Compute sin, cos, tan
print("Sine:", np.sin(angles_rad))
print("Cosine:", np.cos(angles_rad))
print("Tangent:", np.tan(angles_rad))

# Inverse functions
x_vals = np.array([0.0, 0.5, 1.0])
print("arcsin (deg):", np.rad2deg(np.arcsin(x_vals)))
print("arccos (deg):", np.rad2deg(np.arccos(x_vals)))
print("arctan (deg):", np.rad2deg(np.arctan(x_vals)))

⚠️ Common Pitfalls

Mistake Why it Happens Fix
❌ Using degrees in trig functions NumPy trig funcs require radians, not degrees Use np.deg2rad() to convert
np.tan(π/2) gives large number tan(π/2) → ∞, division by zero Handle or avoid vertical asymptotes
❌ Inverse functions outside domain arcsin, arccos only accept [-1, 1] Clip values or validate input
❌ Forgetting shape broadcasting Mismatched shapes in trigonometric calculations Ensure input shapes match

Tips and Best Practices

  • Use np.linspace(0, 2*np.pi, n) to create smooth angle arrays for plotting.

  • Always convert degrees to radians with np.deg2rad() before passing to np.sin, np.cos, etc.

  • Use arctan2(y, x) over arctan(y/x) to avoid divide-by-zero and quadrant issues.

  • Combine np.hypot(x, y) and arctan2 to convert Cartesian → polar coordinates.


Summary Table

Function Description Input Range Output Range
np.sin(x) Sine Any [-1, 1]
np.cos(x) Cosine Any [-1, 1]
np.tan(x) Tangent Any ℝ (asymptotes)
np.arcsin(x) Inverse sine [-1, 1] [-π/2, π/2]
np.arccos(x) Inverse cosine [-1, 1] [0, π]
np.arctan(x) Inverse tangent [-π/2, π/2]
np.arctan2(y,x) Full-plane inverse tangent ℝ, ℝ [-π, π]

Conclusion

The NumPy trigonometric ufuncs make it easy to perform fast, vectorized computations involving angles and periodic functions. Whether you’re modeling waves, working with geometry, or analyzing signals, these functions are your foundation.

From sine waves to full 2D vector angle analysis, NumPy has you covered — just remember: angles in radians and watch for domain limits!