Trigonometry is essential for various programming tasks, including computer graphics, physics simulations, and signal processing. Python provides robust support for trigonometric calculations through its built-in math module for scalar values and the external numpy library for high-performance array processing.
This guide explains how to access these tools, handle angle conversions, and choose the right library for your specific needs.
Using the Standard math Module
Python comes with a built-in math module that requires no installation. It is ideal for performing calculations on single numbers (scalars).
To access these tools, simply import the module.
import math
sin_val = math.sin(0.5)
cos_val = math.cos(0.5)
tan_val = math.tan(0.5)
print(f"Sin: {sin_val:.4f}")
print(f"Cos: {cos_val:.4f}")
print(f"Tan: {tan_val:.4f}")Output:
Sin: 0.4794
Cos: 0.8776
Tan: 0.5463Handling Angles: Degrees vs. Radians
A common mistake in Python trigonometry is passing degrees directly into functions like sin() or cos(). Python's trigonometric functions always expect radians.
To work with degrees, you must first convert them.
import math
degrees = 90
wrong_result = math.sin(degrees)
print(f"Sin(90) raw input: {wrong_result:.4f}")
radians = math.radians(degrees)
correct_result = math.sin(radians)
print(f"Sin(90) converted: {correct_result:.4f}")
back_to_degrees = math.degrees(radians)
print(f"Converted back: {back_to_degrees}")Output:
Sin(90) raw input: 0.8940
Sin(90) converted: 1.0000
Converted back: 90.0Using numpy for Array Calculations
If you need to perform calculations on a large list of angles (e.g., for data science or graphing), the standard math module is inefficient because it cannot handle lists directly. Instead, use numpy.
import math
import numpy as np
angles = [0, np.pi/4, np.pi/2]
try:
print(math.sin(angles))
except TypeError as e:
print(f"Error: {e}")
sin_values = np.sin(angles)
print(f"NumPy Sine Values: {sin_values}")Output:
Error: must be real number, not list
NumPy Sine Values: [0. 0.70710678 1. ]Common Trigonometric Functions
Both libraries generally share the same function names. Here is a quick reference for the most commonly used tools.
Primary Functions
sin(x): Sinecos(x): Cosinetan(x): Tangent
Inverse Functions (Arc)
Used to recover an angle from a ratio.
asin(x): Arcsineacos(x): Arccosineatan(x): Arctangent
Hyperbolic Functions
Used in complex analysis and physics.
sinh(x): Hyperbolic Sinecosh(x): Hyperbolic Cosine
import math
angle_rad = math.asin(0.5)
angle_deg = math.degrees(angle_rad)
print(f"Radians: {angle_rad:.4f}")
print(f"Degrees: {angle_deg:.1f}")Output:
Radians: 0.5236
Degrees: 30.0Conclusion
To access trigonometric tools in Python:
- Import
mathfor standard, single-value calculations. - Import
numpyfor high-performance array operations. - Convert Angles: Always convert degrees to radians using
math.radians()ornp.deg2rad()before passing them to trigonometric functions.