How to use trigonometry in Python

Learn how to use trigonometry in Python with our guide. Discover methods, tips, real-world applications, and how to debug common errors.

How to use trigonometry in Python
Published on: 
Mon
Apr 6, 2026
Updated on: 
Wed
Apr 8, 2026
The Replit Team

Trigonometry is essential for graphics, physics, and data analysis. Python’s math module simplifies these complex calculations and lets you solve geometric problems with just a few lines of code.

In this article, you'll explore key techniques and practical tips. We'll cover real-world applications and provide advice to debug your code, which helps you use these functions confidently.

Basic trigonometric functions with the math module

import math

# Calculate sine, cosine, and tangent of 45 degrees (π/4 radians)
angle = math.pi / 4 # 45 degrees in radians
print(f"sin(45°) = {math.sin(angle):.4f}")
print(f"cos(45°) = {math.cos(angle):.4f}")
print(f"tan(45°) = {math.tan(angle):.4f}")--OUTPUT--sin(45°) = 0.7071
cos(45°) = 0.7071
tan(45°) = 1.0000

The math module's trigonometric functions operate on radians, not degrees. This is why the code first defines the angle as math.pi / 4, which is the radian equivalent of 45 degrees. This conversion is a fundamental step before performing any calculations.

With the angle correctly set in radians, you can directly call functions like math.sin(), math.cos(), and math.tan(). The example calculates these values for the 45-degree angle, demonstrating how to get the core trigonometric ratios needed for various geometric and physics-based applications.

Beyond basic trigonometry

Building on these fundamentals, you can tackle more complex scenarios like batch operations with numpy, solving for unknown sides, and converting between degrees and radians.

Using numpy for vectorized trigonometric operations

import numpy as np

angles = np.array([0, np.pi/6, np.pi/4, np.pi/3, np.pi/2]) # Array of angles
sines = np.sin(angles)
cosines = np.cos(angles)
print("Angles (radians):", angles)
print("Sines:", sines)
print("Cosines:", cosines)--OUTPUT--Angles (radians): [0. 0.52359878 0.78539816 1.04719755 1.57079633]
Sines: [0. 0.5 0.70710678 0.8660254 1. ]
Cosines: [1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01
6.12323400e-17]

When you need to run trigonometric functions on a batch of angles, the numpy library is a powerful tool. It allows for vectorized operations, which means you can apply a function like np.sin() to an entire array of values at once instead of looping through them individually.

The code demonstrates this by creating a numpy array of several angles and then calculating all their sines and cosines with single calls to np.sin(angles) and np.cos(angles). This approach is significantly more efficient and readable, especially with large datasets.

Calculating angles and sides in triangles

import math

# Law of cosines to find the third side of a triangle
a, b = 5, 7
angle_C = math.radians(60) # 60 degrees in radians
c = math.sqrt(a**2 + b**2 - 2*a*b*math.cos(angle_C))
# Find angle A using inverse cosine
angle_A = math.acos((b**2 + c**2 - a**2) / (2*b*c))
print(f"Side c = {c:.2f}, Angle A = {math.degrees(angle_A):.2f} degrees")--OUTPUT--Side c = 5.74, Angle A = 51.06 degrees

This example applies the Law of Cosines to solve for unknown sides and angles in a triangle. First, it calculates the length of side c using the lengths of sides a and b and the angle between them. The math.sqrt() function is then used to get the final length.

  • You can find unknown angles with inverse trigonometric functions like math.acos().
  • The code also introduces math.radians() and math.degrees(), which provide a direct way to handle angle conversions.

Working with degrees and radians conversions

import math

angles_degrees = [0, 30, 45, 60, 90, 180, 360]
for angle in angles_degrees:
angle_rad = math.radians(angle)
sin_value = math.sin(angle_rad)
cos_value = math.cos(angle_rad)
print(f"{angle:3d}° = {angle_rad:.4f} rad: sin = {sin_value:.4f}, cos = {cos_value:.4f}")--OUTPUT--0° = 0.0000 rad: sin = 0.0000, cos = 1.0000
30° = 0.5236 rad: sin = 0.5000, cos = 0.8660
45° = 0.7854 rad: sin = 0.7071, cos = 0.7071
60° = 1.0472 rad: sin = 0.8660, cos = 0.5000
90° = 1.5708 rad: sin = 1.0000, cos = 0.0000
180° = 3.1416 rad: sin = 0.0000, cos = -1.0000
360° = 6.2832 rad: sin = 0.0000, cos = 1.0000

Since Python's trigonometric functions require radians, you'll often need to convert from degrees. This example demonstrates a practical workflow for handling multiple angles at once.

  • The code iterates through a list of angles provided in degrees.
  • Inside the loop, math.radians() converts each angle before it's passed to math.sin() and math.cos().

This approach ensures your calculations are accurate when your input data is in a more human-readable format like degrees.

Advanced trigonometric techniques

These fundamental operations open the door to more advanced applications, including converting between coordinate systems, working with complex numbers, and visualizing functions.

Converting between polar and cartesian coordinates

import math

# Convert cartesian (x,y) to polar (r,θ)
x, y = 3, 4
r = math.sqrt(x**2 + y**2)
theta = math.atan2(y, x)

# Convert polar back to cartesian
x_new = r * math.cos(theta)
y_new = r * math.sin(theta)

print(f"Cartesian: ({x}, {y}) → Polar: ({r:.2f}, {theta:.2f} rad)")
print(f"Polar: ({r:.2f}, {theta:.2f} rad) → Cartesian: ({x_new:.2f}, {y_new:.2f})")--OUTPUT--Cartesian: (3, 4) → Polar: (5.00, 0.93 rad)
Polar: (5.00, 0.93 rad) → Cartesian: (3.00, 4.00)

Trigonometry is key for converting between coordinate systems, a common task in graphics and physics. The code first converts a Cartesian point (x, y) to its polar form (r, θ). The radius r is found using the Pythagorean theorem with math.sqrt().

  • The angle θ is calculated with math.atan2(y, x). This function is particularly useful because it correctly determines the angle's quadrant, making it more robust than a simple math.atan(y/x).
  • Converting back is straightforward, using the standard formulas x = r * math.cos(θ) and y = r * math.sin(θ).

Using complex numbers with Euler's formula

import math
import cmath

# Euler's formula: e^(iθ) = cos(θ) + i sin(θ)
theta = math.pi / 3 # 60 degrees
z = cmath.exp(complex(0, theta))
print(f"e^(i*π/3) = {z}")
print(f"cos(π/3) + i*sin(π/3) = {math.cos(theta)} + {math.sin(theta)}i")
print(f"Euler's identity: e^(i*π) + 1 = {cmath.exp(complex(0, math.pi)) + 1}")--OUTPUT--e^(i*π/3) = (0.5+0.8660254037844386j)
cos(π/3) + i*sin(π/3) = 0.5 + 0.8660254037844386i
Euler's identity: e^(i*π) + 1 = (-1+1.2246467991473532e-16j)

The cmath module is your tool for applying trigonometry to complex numbers. It's essential for working with Euler's formula, which elegantly links exponential functions with sine and cosine. The code uses cmath.exp() to compute e raised to an imaginary power, directly implementing one side of the formula.

  • You need cmath because the standard math library can't operate on complex values.
  • The code confirms the formula by showing that the result of cmath.exp(complex(0, theta)) matches the manual calculation of cos(θ) + i*sin(θ).
  • It also demonstrates Euler's identity, a famous case where e^(iπ) + 1 resolves to zero, accounting for minor floating-point inaccuracies.

Visualizing trigonometric functions with matplotlib

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2*np.pi, 100)
plt.figure(figsize=(10, 5))
plt.plot(x, np.sin(x), label='sin(x)')
plt.plot(x, np.cos(x), label='cos(x)')
plt.plot(x, np.tan(x), label='tan(x)', linestyle='--')
plt.grid(True)
plt.legend()
plt.title('Trigonometric Functions')
plt.xlabel('x (radians)')
plt.ylim(-2, 2)
plt.show()--OUTPUT--[This would display a graph showing the sine, cosine, and tangent functions plotted over the range 0 to 2π]

Visualizing functions helps you understand their behavior. This code combines numpy for data generation and matplotlib for plotting to create a graph of the core trigonometric functions, making their cyclical nature easy to see.

  • First, np.linspace() creates 100 evenly spaced points from 0 to 2π to serve as the x-axis.
  • Next, plt.plot() is used three times to draw the sine, cosine, and tangent waves across that range.
  • Functions like plt.legend() and plt.grid() add clarity, while plt.ylim() constrains the y-axis to keep the plot readable.

Move faster with Replit

Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. This lets you move from learning individual techniques to building complete applications.

Describe what you want to build, and Agent 4 handles everything from writing the code to connecting databases and deploying it live. Instead of piecing together functions, you can describe the final tool you want and let the Agent build it:

  • A coordinate conversion utility that takes (x, y) inputs and displays the corresponding polar coordinates (r, θ) for physics simulations.
  • A triangle calculator that solves for missing sides and angles using the Law of Cosines, perfect for engineering or design tasks.
  • An interactive dashboard that visualizes sine and cosine waves, letting you adjust frequency and amplitude to see the changes in real time.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

Even with powerful tools, you can run into a few common pitfalls when applying trigonometry in Python.

Common error when mixing degrees and radians

A frequent pitfall is passing a degree value directly to a function like math.sin(). Since Python's trigonometric functions expect radians, this produces a mathematically correct but entirely unexpected result. The code below shows what happens when you forget this conversion.

import math

# Attempting to find the sine of 45 degrees
angle_in_degrees = 45
sin_value = math.sin(angle_in_degrees)
print(f"sin(45°) = {sin_value:.4f}") # Result is incorrect: 0.8509

The function treats the input 45 as radians, not degrees, which is an angle of over 2500°. That's why the result is unexpected. The fix requires an explicit conversion, as the next example demonstrates.

import math

# Correctly converting degrees to radians first
angle_in_degrees = 45
angle_in_radians = math.radians(angle_in_degrees)
sin_value = math.sin(angle_in_radians)
print(f"sin(45°) = {sin_value:.4f}") # Correct result: 0.7071

The fix is to explicitly convert degrees to radians before passing the value to a trigonometric function. By calling math.radians() on the angle first, you ensure math.sin() receives the correct input format and returns the expected result. You'll want to keep an eye out for this issue whenever your application handles angles from user input or external datasets, as they are often provided in degrees rather than radians.

Handling division by zero in tan() at π/2

The tan() function is undefined at π/2 radians (90°) and its multiples because the calculation involves division by zero. This can cause unexpected behavior, often returning extremely large numbers instead of a clear error. The code below demonstrates what happens when you calculate the tangent at these critical points.

import math

# Calculate tangent at various angles
angles = [0, math.pi/4, math.pi/2, 3*math.pi/4, math.pi]
for angle in angles:
tan_value = math.tan(angle)
print(f"tan({angle:.2f}) = {tan_value:.4f}")

Because of floating-point precision, math.tan(math.pi/2) doesn't error out. It returns a huge number that can break your logic. The code below shows how you can check for these cases and handle them gracefully.

import math

# Safely calculate tangent at various angles
angles = [0, math.pi/4, math.pi/2, 3*math.pi/4, math.pi]
for angle in angles:
try:
tan_value = math.tan(angle)
print(f"tan({angle:.2f}) = {tan_value:.4f}")
except ValueError:
print(f"tan({angle:.2f}) = undefined")

A robust way to handle this is by wrapping the math.tan() call in a try...except block. This approach anticipates that certain inputs, like π/2, will cause issues. Instead of returning a massive number that could disrupt your program's logic, the except block catches the problem and lets you substitute a more meaningful output. This defensive coding practice is crucial whenever a function's domain has known limitations.

Avoiding domain errors with asin() and acos()

The inverse sine and cosine functions, math.asin() and math.acos(), only work with inputs between -1 and 1. Feeding them a value outside this range will raise a ValueError and crash your program. The following code demonstrates this common error.

import math

# Attempting to calculate arcsine/arccosine with values outside domain
values = [-1.5, -1.0, 0, 1.0, 1.2]
for val in values:
asin_value = math.asin(val)
acos_value = math.acos(val)
print(f"asin({val}) = {asin_value:.4f}, acos({val}) = {acos_value:.4f}")

The loop attempts to compute the arcsine and arccosine for values like -1.5 and 1.2. Because these numbers fall outside the functions' valid domain, the program crashes. The following code shows how to handle this gracefully.

import math

# Safely calculating arcsine/arccosine with bounds checking
values = [-1.5, -1.0, 0, 1.0, 1.2]
for val in values:
try:
asin_value = math.asin(val)
acos_value = math.acos(val)
print(f"asin({val}) = {asin_value:.4f}, acos({val}) = {acos_value:.4f}")
except ValueError as e:
print(f"Error with value {val}: {e}")

To prevent crashes, you can wrap the math.asin() and math.acos() calls in a try...except block. This approach catches the ValueError when an input is invalid, allowing your program to handle the error gracefully instead of stopping. It's especially useful when dealing with calculations that might result in floating-point numbers slightly outside the valid [-1, 1] domain—a common source of unexpected errors.

Real-world applications

With a solid grasp of these functions and their common pitfalls, you can build powerful tools for physics simulations and geographic calculations.

Simulating pendulum motion with math.cos() and math.sin()

You can simulate the rhythmic swing of a pendulum by using math.cos() to calculate its angle at any point in time and then applying both math.sin() and math.cos() to determine its exact (x, y) position.

import math

# Simulate pendulum motion at different times
length = 1.0 # length of pendulum in meters
max_angle = math.radians(30) # maximum angle (30 degrees)

# Calculate positions at different points in oscillation cycle
for t in [0, 0.25, 0.5, 0.75, 1.0]:
angle = max_angle * math.cos(2 * math.pi * t)
x = length * math.sin(angle)
y = -length * math.cos(angle)
print(f"At {t} of cycle: Position=({x:.3f}, {y:.3f})")

This code models a pendulum's position over one full swing. It calculates the bob's (x, y) coordinates at different moments in time, represented by t.

  • The core of the simulation is angle = max_angle * math.cos(2 * math.pi * t), which uses the cosine function to create a natural back-and-forth motion.
  • The final two lines convert this angle into Cartesian coordinates, with y being negative to represent the pendulum hanging down from its pivot point.

Calculating geographic distances with the haversine formula

Trigonometry also powers geographic calculations through the haversine formula, which finds the great-circle distance between two points on Earth from their latitude and longitude.

import math

# Calculate distance between two points on Earth
def haversine(lat1, lon1, lat2, lon2):
R = 6371.0 # Earth's radius in km
dLat = math.radians(lat2 - lat1)
dLon = math.radians(lon2 - lon1)
a = math.sin(dLat/2)**2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dLon/2)**2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
return R * c

# Distance from New York to London
distance = haversine(40.7128, -74.0060, 51.5074, -0.1278)
print(f"Distance from New York to London: {distance:.1f} km")

The haversine function calculates the shortest distance over the Earth's surface between two coordinates. It's a practical application of trigonometry for solving real-world problems.

  • First, it converts the latitude and longitude differences from degrees to radians, since Python's math functions require them.
  • The core logic uses math.sin() and math.cos() to implement the haversine formula itself.
  • Finally, math.atan2() calculates the central angle, which is then multiplied by the Earth's radius to return the final distance in kilometers.

Get started with Replit

Turn your knowledge into a tool. Tell Replit Agent: "Build a haversine distance calculator" or "Create a web app that converts Cartesian to polar coordinates."

The Agent writes the code, tests for errors, and deploys your app. You just provide the instructions. Start building with Replit.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.