
If you’ve ever worked with mathematical computations in Python, you know how important NumPy trigonometric functions are for scientific computing and data analysis. NumPy trigonometric functions provide a powerful and efficient way to perform trigonometric calculations on arrays, making complex mathematical operations simple and fast. Whether you’re calculating sine, cosine, tangent, or their inverse functions, NumPy trigonometric functions handle everything with remarkable speed and precision, operating on entire arrays at once rather than individual elements.
NumPy trigonometric functions are essential tools in the NumPy library that allow you to perform trigonometric operations on arrays and scalars. These functions work with angles measured in radians by default and include all standard trigonometric operations like sine (sin), cosine (cos), tangent (tan), and their inverse and hyperbolic counterparts.
Before diving into NumPy trigonometric functions, it’s crucial to understand that NumPy works with radians, not degrees. This is a common source of confusion for beginners. One complete circle equals 2π radians or 360 degrees.
To convert between degrees and radians, NumPy provides helpful conversion functions:
import numpy as np
# Convert degrees to radians
angle_degrees = 90
angle_radians = np.deg2rad(angle_degrees)
print(f"{angle_degrees} degrees = {angle_radians} radians")
# Output: 90 degrees = 1.5707963267948966 radians
# Convert radians to degrees
angle_rad = np.pi / 4
angle_deg = np.rad2deg(angle_rad)
print(f"{angle_rad} radians = {angle_deg} degrees")
# Output: 0.7853981633974483 radians = 45.0 degrees
**
**
The np.sin() function calculates the sine of angles provided in radians. The sine function returns values between -1 and 1, representing the y-coordinate on the unit circle.
Syntax: numpy.sin(x, out=None, where=True)
Parameters:
x: Input array containing angles in radiansout: Optional output array for storing resultswhere: Condition to apply the functionimport numpy as np
# Single value
angle = np.pi / 2
result = np.sin(angle)
print(f"sin(π/2) = {result}")
# Output: sin(π/2) = 1.0
# Array of values
angles = np.array([0, np.pi/6, np.pi/4, np.pi/3, np.pi/2])
sine_values = np.sin(angles)
print("Sine values:", sine_values)
# Output: Sine values: [0. 0.5 0.70710678 0.8660254 1. ]
The np.cos() function computes the cosine of angles in radians. Cosine represents the x-coordinate on the unit circle and also ranges from -1 to 1.
Syntax: numpy.cos(x, out=None, where=True)
import numpy as np
# Cosine of common angles
angles = np.array([0, np.pi/4, np.pi/2, np.pi])
cosine_values = np.cos(angles)
print("Cosine values:", cosine_values)
# Output: Cosine values: [ 1.00000000e+00 7.07106781e-01 6.12323400e-17 -1.00000000e+00]
# Note: π/2 gives a very small number (close to 0) due to floating-point precision
**
**
The np.tan() function calculates the tangent of angles, which is the ratio of sine to cosine (sin/cos). Unlike sine and cosine, tangent can take any real value and has undefined points where cosine equals zero.
Syntax: numpy.tan(x, out=None, where=True)
import numpy as np
# Tangent of various angles
angles = np.array([0, np.pi/6, np.pi/4, np.pi/3])
tangent_values = np.tan(angles)
print("Tangent values:", tangent_values)
# Output: Tangent values: [0. 0.57735027 1. 1.73205081]
# Tangent of π/4 equals 1
print(f"tan(45°) = {np.tan(np.deg2rad(45))}")
# Output: tan(45°) = 0.9999999999999999
Inverse trigonometric functions, also called arc functions, return the angle when you provide the trigonometric ratio. These NumPy trigonometric functions are extremely useful when you need to find angles from known ratios.
The np.arcsin() function returns the arcsine (inverse sine) of input values. The input must be in the range [-1, 1], and the output is in radians ranging from -π/2 to π/2.
Syntax: numpy.arcsin(x, out=None, where=True)
import numpy as np
# Arcsine of values
values = np.array([0, 0.5, 0.707, 1])
arc_sine = np.arcsin(values)
print("Arcsine (radians):", arc_sine)
# Output: Arcsine (radians): [0. 0.52359878 0.78605436 1.57079633]
# Convert to degrees
print("Arcsine (degrees):", np.rad2deg(arc_sine))
# Output: Arcsine (degrees): [ 0. 30.00007951 45.02922674 90. ]
**
**
The np.arccos() function computes the arccosine (inverse cosine) of input values. Input values must be between -1 and 1, and the output ranges from 0 to π radians.
Syntax: numpy.arccos(x, out=None, where=True)
import numpy as np
# Arccosine calculations
values = np.array([1, 0.866, 0.5, 0])
arc_cosine = np.arccos(values)
print("Arccosine (radians):", arc_cosine)
# Output: Arccosine (radians): [0. 0.52401872 1.04719755 1.57079633]
# In degrees
print("Arccosine (degrees):", np.rad2deg(arc_cosine))
# Output: Arccosine (degrees): [ 0. 30.01198362 60. 90. ]
The np.arctan() function returns the arctangent (inverse tangent) of input values. Unlike arcsine and arccosine, arctan accepts any real number as input and returns values from -π/2 to π/2.
Syntax: numpy.arctan(x, out=None, where=True)
import numpy as np
# Arctangent examples
values = np.array([0, 0.577, 1, 1.732])
arc_tangent = np.arctan(values)
print("Arctangent (radians):", arc_tangent)
# Output: Arctangent (radians): [0. 0.52148835 0.78539816 1.04692836]
# Converting to degrees
print("Arctangent (degrees):", np.rad2deg(arc_tangent))
# Output: Arctangent (degrees): [ 0. 29.8810992 45. 59.99484548]
**
**
The np.arctan2() function is a special variant that takes two arguments (y, x) and returns the angle in the correct quadrant. This is particularly useful because it considers the signs of both arguments to determine the proper quadrant, returning values from -π to π.
Syntax: numpy.arctan2(y, x, out=None, where=True)
import numpy as np
# arctan2 for different quadrants
y_values = np.array([1, 1, -1, -1])
x_values = np.array([1, -1, -1, 1])
angles = np.arctan2(y_values, x_values)
print("Angles (radians):", angles)
# Output: Angles (radians): [ 0.78539816 2.35619449 -2.35619449 -0.78539816]
print("Angles (degrees):", np.rad2deg(angles))
# Output: Angles (degrees): [ 45. 135. -135. -45.]
Hyperbolic functions are analogues of trigonometric functions but for a hyperbola instead of a circle. NumPy trigonometric functions include these hyperbolic variants which are commonly used in calculus, physics, and engineering.
The np.sinh() function calculates the hyperbolic sine, defined as (e^x - e^(-x))/2. Unlike regular sine, hyperbolic sine can produce any real number.
Syntax: numpy.sinh(x, out=None, where=True)
import numpy as np
# Hyperbolic sine
values = np.array([0, 0.5, 1, 2])
hyp_sine = np.sinh(values)
print("Hyperbolic sine:", hyp_sine)
# Output: Hyperbolic sine: [0. 0.52109531 1.17520119 3.62686041]
**
**
The np.cosh() function computes the hyperbolic cosine, defined as (e^x + e^(-x))/2. The minimum value of cosh is 1 at x=0.
Syntax: numpy.cosh(x, out=None, where=True)
import numpy as np
# Hyperbolic cosine
values = np.array([0, 0.5, 1, 2])
hyp_cosine = np.cosh(values)
print("Hyperbolic cosine:", hyp_cosine)
# Output: Hyperbolic cosine: [1. 1.12762597 1.54308063 3.76219569]
The np.tanh() function returns the hyperbolic tangent, defined as sinh(x)/cosh(x). The output ranges from -1 to 1, making it useful in machine learning activation functions.
Syntax: numpy.tanh(x, out=None, where=True)
import numpy as np
# Hyperbolic tangent
values = np.array([-2, -1, 0, 1, 2])
hyp_tangent = np.tanh(values)
print("Hyperbolic tangent:", hyp_tangent)
# Output: Hyperbolic tangent: [-0.96402758 -0.76159416 0. 0.76159416 0.96402758]
Just like regular trigonometric functions, hyperbolic functions also have their inverses. These NumPy trigonometric functions are used in various mathematical and scientific applications.
The np.arcsinh() function computes the inverse hyperbolic sine. It accepts any real number and returns any real number.
Syntax: numpy.arcsinh(x, out=None, where=True)
import numpy as np
# Inverse hyperbolic sine
values = np.array([0, 1, 2, 3])
inv_hyp_sine = np.arcsinh(values)
print("Inverse hyperbolic sine:", inv_hyp_sine)
# Output: Inverse hyperbolic sine: [0. 0.88137359 1.44363548 1.81844646]
**
**
The np.arccosh() function returns the inverse hyperbolic cosine. The input must be greater than or equal to 1.
Syntax: numpy.arccosh(x, out=None, where=True)
import numpy as np
# Inverse hyperbolic cosine
values = np.array([1, 2, 3, 4])
inv_hyp_cosine = np.arccosh(values)
print("Inverse hyperbolic cosine:", inv_hyp_cosine)
# Output: Inverse hyperbolic cosine: [0. 1.3169579 1.76274717 2.06343707]
The np.arctanh() function computes the inverse hyperbolic tangent. Input values must be in the range (-1, 1), excluding -1 and 1.
Syntax: numpy.arctanh(x, out=None, where=True)
import numpy as np
# Inverse hyperbolic tangent
values = np.array([0, 0.5, 0.75, 0.9])
inv_hyp_tangent = np.arctanh(values)
print("Inverse hyperbolic tangent:", inv_hyp_tangent)
# Output: Inverse hyperbolic tangent: [0. 0.54930614 0.97295507 1.47221949]
One of the greatest advantages of NumPy trigonometric functions is their ability to operate on entire arrays efficiently. This vectorized operation is much faster than using loops with standard Python math functions.
import numpy as np
# Create an array of angles from 0 to 2π
angles = np.linspace(0, 2*np.pi, 12)
print("Angles:", angles)
# Calculate sine for all angles at once
sine_wave = np.sin(angles)
print("\nSine values:", sine_wave)
# Calculate cosine for all angles
cosine_wave = np.cos(angles)
print("\nCosine values:", cosine_wave)
# Create a 2D array
matrix_angles = np.array([[0, np.pi/4], [np.pi/2, np.pi]])
print("\n2D Array of angles:\n", matrix_angles)
# Apply sine to 2D array
sine_matrix = np.sin(matrix_angles)
print("\nSine of 2D array:\n", sine_matrix)
Here’s a complete example demonstrating various NumPy trigonometric functions in a practical scenario where we analyze and manipulate trigonometric waves:
import numpy as np
# Create a range of angles from 0 to 4π with 50 points
angles = np.linspace(0, 4*np.pi, 50)
print("=" * 60)
print("TRIGONOMETRIC WAVE ANALYSIS")
print("=" * 60)
# Calculate basic trigonometric functions
sine_wave = np.sin(angles)
cosine_wave = np.cos(angles)
tangent_wave = np.tan(angles)
print("\nBasic Trigonometric Functions:")
print(f"First 5 angles (radians): {angles[:5]}")
print(f"Sine values: {sine_wave[:5]}")
print(f"Cosine values: {cosine_wave[:5]}")
print(f"Tangent values: {tangent_wave[:5]}")
# Find peaks in sine wave (where sine = 1)
sine_peaks_indices = np.where(np.abs(sine_wave - 1) < 0.01)[0]
print(f"\nSine wave peaks occur at indices: {sine_peaks_indices}")
print(f"Corresponding angles (radians): {angles[sine_peaks_indices]}")
print(f"Corresponding angles (degrees): {np.rad2deg(angles[sine_peaks_indices])}")
# Inverse trigonometric functions
sample_values = np.array([0, 0.5, 0.707, 0.866, 1.0])
arcsin_values = np.arcsin(sample_values)
arccos_values = np.arccos(sample_values)
arctan_values = np.arctan(sample_values)
print("\n" + "-" * 60)
print("Inverse Trigonometric Functions:")
print("-" * 60)
print(f"Input values: {sample_values}")
print(f"Arcsine (radians): {arcsin_values}")
print(f"Arcsine (degrees): {np.rad2deg(arcsin_values)}")
print(f"Arccosine (radians): {arccos_values}")
print(f"Arccosine (degrees): {np.rad2deg(arccos_values)}")
print(f"Arctangent (radians): {arctan_values}")
print(f"Arctangent (degrees): {np.rad2deg(arctan_values)}")
# Demonstrate arctan2 for quadrant detection
x_coords = np.array([1, -1, -1, 1, 0, 0])
y_coords = np.array([1, 1, -1, -1, 1, -1])
quadrant_angles = np.arctan2(y_coords, x_coords)
print("\n" + "-" * 60)
print("Quadrant Detection with arctan2:")
print("-" * 60)
for i in range(len(x_coords)):
print(f"Point ({x_coords[i]:2}, {y_coords[i]:2}) -> "
f"Angle: {np.rad2deg(quadrant_angles[i]):7.2f}°")
# Hyperbolic functions
hyp_values = np.array([0, 0.5, 1.0, 1.5, 2.0])
sinh_vals = np.sinh(hyp_values)
cosh_vals = np.cosh(hyp_values)
tanh_vals = np.tanh(hyp_values)
print("\n" + "-" * 60)
print("Hyperbolic Trigonometric Functions:")
print("-" * 60)
print(f"Input values: {hyp_values}")
print(f"Sinh: {sinh_vals}")
print(f"Cosh: {cosh_vals}")
print(f"Tanh: {tanh_vals}")
# Verify identity: cosh²(x) - sinh²(x) = 1
identity_check = cosh_vals**2 - sinh_vals**2
print(f"\nVerifying identity cosh²(x) - sinh²(x) = 1:")
print(f"Results: {identity_check}")
print(f"All close to 1: {np.allclose(identity_check, 1)}")
# Inverse hyperbolic functions
inv_hyp_values = np.array([0, 0.5, 1.0, 2.0, 5.0])
arcsinh_vals = np.arcsinh(inv_hyp_values)
arccosh_vals = np.arccosh(np.array([1.0, 2.0, 3.0, 5.0, 10.0]))
arctanh_vals = np.arctanh(np.array([0, 0.25, 0.5, 0.75, 0.9]))
print("\n" + "-" * 60)
print("Inverse Hyperbolic Functions:")
print("-" * 60)
print(f"arcsinh({inv_hyp_values}): {arcsinh_vals}")
print(f"arccosh([1, 2, 3, 5, 10]): {arccosh_vals}")
print(f"arctanh([0, 0.25, 0.5, 0.75, 0.9]): {arctanh_vals}")
# Conversion between degrees and radians
degree_angles = np.array([0, 30, 45, 60, 90, 180, 270, 360])
radian_angles = np.deg2rad(degree_angles)
back_to_degrees = np.rad2deg(radian_angles)
print("\n" + "-" * 60)
print("Degree-Radian Conversions:")
print("-" * 60)
print(f"Degrees: {degree_angles}")
print(f"Radians: {radian_angles}")
print(f"Back to degrees: {back_to_degrees}")
# Calculate phase difference between two waves
wave1 = np.sin(angles)
wave2 = np.sin(angles + np.pi/4) # Wave shifted by 45 degrees
# Find where waves intersect (approximately)
intersections = np.where(np.abs(wave1 - wave2) < 0.1)[0][:5]
print("\n" + "-" * 60)
print("Wave Intersection Analysis:")
print("-" * 60)
print(f"First 5 intersection points at indices: {intersections}")
print(f"Angles (degrees): {np.rad2deg(angles[intersections])}")
# Statistical analysis of trigonometric waves
print("\n" + "-" * 60)
print("Statistical Analysis of Sine Wave:")
print("-" * 60)
print(f"Mean: {np.mean(sine_wave):.6f}")
print(f"Standard Deviation: {np.std(sine_wave):.6f}")
print(f"Minimum: {np.min(sine_wave):.6f}")
print(f"Maximum: {np.max(sine_wave):.6f}")
print(f"Range: {np.ptp(sine_wave):.6f}")
print("\n" + "=" * 60)
print("ANALYSIS COMPLETE")
print("=" * 60)
Output:
============================================================
TRIGONOMETRIC WAVE ANALYSIS
============================================================
Basic Trigonometric Functions:
First 5 angles (radians): [0. 0.25641026 0.51282051 0.76923077 1.02564103]
Sine values: [0. 0.25333234 0.49026082 0.69670671 0.85286853]
Cosine values: [ 1. 0.96734524 0.87157577 0.71735609 0.52216459]
Tangent values: [0. 0.26189637 0.56243491 0.97125069 1.63343404]
Sine wave peaks occur at indices: [6]
Corresponding angles (radians): [1.53846154]
Corresponding angles (degrees): [88.16326531]
------------------------------------------------------------
Inverse Trigonometric Functions:
------------------------------------------------------------
Input values: [0. 0.5 0.707 0.866 1. ]
Arcsine (radians): [0. 0.52359878 0.78605436 1.04719755 1.57079633]
Arcsine (degrees): [ 0. 30.00007951 45.02922674 60. 90. ]
Arccosine (radians): [1.57079633 1.04719755 0.78474197 0.52359878 0. ]
Arccosine (degrees): [90. 60. 44.97077326 30. 0. ]
Arctangent (radians): [0. 0.46364761 0.61572651 0.71381169 0.78539816]
Arctangent (degrees): [ 0. 26.56505118 35.28116404 40.89339465 45. ]
------------------------------------------------------------
Quadrant Detection with arctan2:
------------------------------------------------------------
Point ( 1, 1) -> Angle: 45.00°
Point (-1, 1) -> Angle: 135.00°
Point (-1, -1) -> Angle: -135.00°
Point ( 1, -1) -> Angle: -45.00°
Point ( 0, 1) -> Angle: 90.00°
Point ( 0, -1) -> Angle: -90.00°
------------------------------------------------------------
Hyperbolic Trigonometric Functions:
------------------------------------------------------------
Input values: [0. 0.5 1. 1.5 2. ]
Sinh: [0. 0.52109531 1.17520119 2.12927946 3.62686041]
Cosh: [1. 1.12762597 1.54308063 2.35240962 3.76219569]
Tanh: [0. 0.46211716 0.76159416 0.90514825 0.96402758]
Verifying identity cosh²(x) - sinh²(x) = 1:
Results: [1. 1. 1. 1. 1.]
All close to 1: True
------------------------------------------------------------
Inverse Hyperbolic Functions:
------------------------------------------------------------
arcsinh([0. 0.5 1. 2. 5. ]): [0. 0.48121183 0.88137359 1.44363548 2.31243834]
arccosh([1, 2, 3, 5, 10]): [0. 1.3169579 1.76274717 2.29243167 2.99322285]
arctanh([0, 0.25, 0.5, 0.75, 0.9]): [0. 0.25541281 0.54930614 0.97295507 1.47221949]
------------------------------------------------------------
Degree-Radian Conversions:
------------------------------------------------------------
Degrees: [ 0 30 45 60 90 180 270 360]
Radians: [0. 0.52359878 0.78539816 1.04719755 1.57079633 3.14159265
4.71238898 6.28318531]
Back to degrees: [ 0. 30. 45. 60. 90. 180. 270. 360.]
------------------------------------------------------------
Wave Intersection Analysis:
------------------------------------------------------------
First 5 intersection points at indices: [38 39 40 41 42]
Angles (degrees): [309.79591837 318.36734694 326.93877551 335.51020408 344.08163265]
------------------------------------------------------------
Statistical Analysis of Sine Wave:
------------------------------------------------------------
Mean: 0.029888
Standard Deviation: 0.711556
Minimum: -0.999890
Maximum: 0.999890
Range: 1.999780
============================================================
ANALYSIS COMPLETE
============================================================
This comprehensive example demonstrates how NumPy trigonometric functions work together to perform complex mathematical analysis. The code shows conversion between degrees and radians, basic and inverse trigonometric functions, hyperbolic functions, quadrant detection with arctan2, and practical wave analysis. All these NumPy trigonometric functions operate efficiently on arrays, making numerical computations fast and straightforward for data scientists, engineers, and mathematicians working with Python.
For more information about NumPy and its mathematical functions, visit the official NumPy documentation.