Python math.tan(): Calculate Tangent Ratios

The math.tan(x) function returns the trigonometric tangent of an angle x expressed in radians. Mathematically, it represents the ratio of the opposite side to the adjacent side in a right-angled triangle ($ rac{\sin(x)}{\cos(x)}$), which also corresponds to the slope of a line with inclination angle x.

Inverse Function: To calculate the angle in radians from a given tangent ratio, use the arc tangent math.atan() or four-quadrant math.atan2(y, x).

Syntax & Parameters 🔝

The math.tan() function is part of the standard math module:

import math

tangent_val = math.tan(x)
Parameter Type Required? Description
x float or int Yes The angle measured strictly in radians. Supports positive, negative, and zero values.

Return Value: Returns a floating-point number (float) representing $ an(x) = rac{\sin(x)}{\cos(x)}$.

Basic Examples in Radians 🔝

Evaluating standard angles in radians:

import math

print("tan(0):        ", math.tan(0))              # 0.0
print("tan(pi/4):     ", math.tan(math.pi / 4))        # 1.0 (45 degrees)
print("tan(1 radian): ", math.tan(1))                  # 1.5574077246549023
print("tan(pi):       ", math.tan(math.pi))            # -1.2246467991473532e-16 (~0.0)
Expected Output
tan(0):         0.0
tan(pi/4):      1.0
tan(1 radian):  1.5574077246549023
tan(pi):       -1.2246467991473532e-16

Converting Degrees to Radians (math.radians) 🔝

Because angles in practical navigation and surveying are expressed in degrees, convert them to radians before passing to math.tan():

import math

angles_deg = [0, 30, 45, 60]

for deg in angles_deg:
    rad = math.radians(deg)
    print(f"tan({deg:2d}°) = {math.tan(rad):.4f}")
Expected Output
tan( 0°) = 0.0000
tan(30°) = 0.5774
tan(45°) = 1.0000
tan(60°) = 1.7321

The 90-Degree Asymptote Floating-Point Trap 🔝

In pure mathematics, $ an(90^\circ) = an( rac{\pi}{2})$ is undefined because $\cos(90^\circ) = 0$ (division by zero vertical asymptote). However, in Python, math.tan(math.radians(90)) does not raise an exception or return infinity:

import math

rad_90 = math.radians(90)
print("tan(90°):", math.tan(rad_90))  # 1.633123935319537e+16
Why doesn't it crash?
Because $\pi$ is an irrational number that cannot be represented exactly in finite 64-bit IEEE 754 binary floats, math.radians(90) yields an approximation slightly different from true $ rac{\pi}{2}$. The cosine is evaluated as approximately 6.12e-17 rather than exact 0, resulting in a gigantic finite number ($pprox 1.63 imes 10^{16}$) rather than a ZeroDivisionError.

Periodicity & Symmetry Properties 🔝

The tangent function exhibits distinct mathematical behaviors:

  • Odd Function Symmetry: $ an(-x) = - an(x)$ — negating the input inverts the sign of the result.
  • Period of π (180 Degrees): While math.sin() and math.cos() repeat every $2\pi$ ($360^\circ$), tangent repeats every $\pi$ ($180^\circ$): $ an(x + \pi) = an(x)$.
  • Full Range: Unlike sine and cosine which are constrained between $[-1, 1]$, the tangent function produces values across $(-\infty, +\infty)$.
import math

theta = 0.85
print("Odd symmetry: ", math.isclose(math.tan(-theta), -math.tan(theta)))  # True
print("Period of pi: ", math.isclose(math.tan(theta + math.pi), math.tan(theta)))  # True

Plotting the Tangent Curve with Matplotlib 🔝

You can visualize the asymptotic curve using Matplotlib, masking large spikes near $\pm rac{\pi}{2}$:

import math
import matplotlib.pyplot as plt

x_vals = [i * 0.05 - 3.0 for i in range(0, 120)]
y_vals = []

for x in x_vals:
    val = math.tan(x)
    # Clamp large values near asymptotes for clean visualization
    y_vals.append(val if -10 < val < 10 else float("nan"))

plt.plot(x_vals, y_vals, label="tan(x)", color="#d93025")
plt.ylim(-8, 8)
plt.title("Trigonometric Tangent Curve")
plt.xlabel("Radians")
plt.ylabel("tan(x)")
plt.grid(True)
plt.show()

Hands-on Exercise: Elevation Height Estimator with Assertions 🔝

In surveying and forestry, the height of a tall building or tree can be measured from the ground using distance $d$ and angle of elevation $ heta$: $$h = d \cdot an( heta) + h_{ ext{observer}}$$ Let's build an elevation height calculator verified with unit assertions:

Python Exercise: Trigonometric Structure Height Estimator
import math

def estimate_structure_height(distance_meters, elevation_degrees, eye_level_meters=1.6):
    if elevation_degrees >= 90 or elevation_degrees <= 0:
        raise ValueError("Elevation angle must be between 0 and 90 degrees.")
        
    theta_rad = math.radians(elevation_degrees)
    height = distance_meters * math.tan(theta_rad) + eye_level_meters
    return round(height, 2)

# Unit Assertions
assert estimate_structure_height(50, 45, 1.6) == 51.60    # tan(45) = 1.0 -> 50 + 1.6
assert estimate_structure_height(50, 30, 1.6) == 30.47    # tan(30) = 0.57735
assert estimate_structure_height(100, 60, 2.0) == 175.21  # tan(60) = 1.73205

print("Building Height (50m away, 45 deg):", estimate_structure_height(50, 45), "meters")
print("Tower Height (100m away, 60 deg):   ", estimate_structure_height(100, 60, 2.0), "meters")
print("All structure height unit assertions passed successfully!")

Practice in Google Colab & GitHub 🔝

Open in Google Colab View on GitHub

Run all math.tan() examples interactively, test the 90-degree asymptote behavior, and verify the trigonometric elevation estimator with unit assertions directly in Google Colab.




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer