Python math.cos(): Calculate Cosine Trigonometry

The math.cos(x) function returns the trigonometric cosine of an angle x measured in radians. The returned value is a floating-point number strictly bounded between -1.0 and 1.0, representing the horizontal coordinate on a standard unit circle.

Companion Functions: For the vertical unit coordinate, see math.sin(). To reverse a cosine ratio back into an angle, use the inverse arc cosine math.acos().

Syntax & Parameters 🔝

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

import math

cosine_val = math.cos(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) in the closed interval $[-1.0, 1.0]$.

Basic Examples in Radians 🔝

Common standard angles in radians evaluated using math.cos():

import math

print("cos(0):       ", math.cos(0))          # 1.0
print("cos(pi):      ", math.cos(math.pi))    # -1.0
print("cos(2*pi):    ", math.cos(2 * math.pi))# 1.0 (full 360-degree rotation)
print("cos(1 radian):", math.cos(1))          # 0.5403023058681398
Expected Output
cos(0):        1.0
cos(pi):       -1.0
cos(2*pi):     1.0
cos(1 radian): 0.5403023058681398

Working with Angles in Degrees (math.radians) 🔝

Most real-world problems (such as maps, compasses, and user interfaces) specify angles in degrees ($0^\circ$ to $360^\circ$). Because math.cos() strictly expects radians, convert degrees first using math.radians():

import math

degrees_list = [0, 60, 120, 180, 240, 300, 360]

for deg in degrees_list:
    rad = math.radians(deg)
    print(f"cos({deg:3d}°) = {math.cos(rad):6.3f}")
Expected Output
cos(  0°) =  1.000
cos( 60°) =  0.500
cos(120°) = -0.500
cos(180°) = -1.000
cos(240°) = -0.500
cos(300°) =  0.500
cos(360°) =  1.000
Conversion Reminder: $1 ext{ radian} = rac{180^\circ}{\pi} pprox 57.2958^\circ$, and $1^\circ = rac{\pi}{180} pprox 0.01745 ext{ radians}$.

Floating-Point Precision at π/2 (90 Degrees) 🔝

Mathematically, $\cos(90^\circ) = \cos( rac{\pi}{2}) = 0$. However, in computer science, $\pi$ is an irrational number represented by a finite 64-bit IEEE 754 floating-point approximation. Therefore, evaluating $\cos(90^\circ)$ yields a tiny near-zero residue:

import math

rad_90 = math.radians(90)
result = math.cos(rad_90)

print("cos(90°) raw:     ", result)  # 6.123233995736766e-17
print("Is close to 0.0? ", math.isclose(result, 0.0, abs_tol=1e-15))  # True

Best Practice: Never check if math.cos(rad) == 0:. Always use math.isclose(math.cos(rad), 0.0, abs_tol=1e-12) when comparing against zero.

Key Mathematical Properties & Identities 🔝

The cosine function satisfies fundamental mathematical symmetries:

  • Even Function Symmetry: $\cos(-x) = \cos(x)$ — negating the angle does not alter the cosine value.
  • Pythagorean Trigonometric Identity: $\sin^2(x) + \cos^2(x) = 1.0$ for any angle $x$.
  • Periodicity: $\cos(x + 2\pi) = \cos(x)$ — repeating indefinitely every $2\pi$ radians ($360^\circ$).
import math

theta = 1.25
# Symmetry check
print(math.cos(-theta) == math.cos(theta))  # True

# Pythagorean identity check
identity = math.sin(theta)**2 + math.cos(theta)**2
print(math.isclose(identity, 1.0))           # True

Plotting the Cosine Wave with Matplotlib 🔝

You can visualize the periodic waveform using Matplotlib or animate curves on a Tkinter Canvas:

import math
import matplotlib.pyplot as plt

x_vals = [i * 0.1 for i in range(0, 70)]  # 0 to 7 radians (~2*pi)
y_vals = [math.cos(x) for x in x_vals]

plt.plot(x_vals, y_vals, label="cos(x)", color="#1a73e8")
plt.axhline(0, color="gray", linewidth=0.8, linestyle="--")
plt.title("Trigonometric Cosine Wave")
plt.xlabel("Radians")
plt.ylabel("cos(x)")
plt.grid(True)
plt.show()

Hands-on Exercise: Polar to Cartesian Vector Decomposition with Assertions 🔝

In physics, game engineering, and robotics, movement vectors specified by radius $r$ and heading angle $ heta$ must be converted into Cartesian coordinates $(x, y)$ using the formulas: $$x = r \cdot \cos( heta), \quad y = r \cdot \sin( heta)$$ Let's build a vector decomposition utility using math.cos() and math.sin() verified with unit assertions:

Python Exercise: 2D Polar-to-Cartesian Vector Converter
import math

def polar_to_cartesian(radius, angle_degrees):
    theta_rad = math.radians(angle_degrees)
    
    x = radius * math.cos(theta_rad)
    y = radius * math.sin(theta_rad)
    
    # Clamp near-zero floating point residues
    x = 0.0 if math.isclose(x, 0.0, abs_tol=1e-12) else x
    y = 0.0 if math.isclose(y, 0.0, abs_tol=1e-12) else y
    
    return round(x, 4), round(y, 4)

# Unit Assertions
assert polar_to_cartesian(10, 0) == (10.0, 0.0)       # East
assert polar_to_cartesian(10, 90) == (0.0, 10.0)      # North
assert polar_to_cartesian(10, 180) == (-10.0, 0.0)    # West
assert polar_to_cartesian(10, 270) == (0.0, -10.0)    # South
assert polar_to_cartesian(10, 45) == (7.0711, 7.0711)  # 45 degrees diagonal

print("Vector (10, 45 deg)  -> (x, y):", polar_to_cartesian(10, 45))
print("Vector (10, 180 deg) -> (x, y):", polar_to_cartesian(10, 180))
print("All vector decomposition assertions passed successfully!")

Practice in Google Colab & GitHub 🔝

Open in Google Colab View on GitHub

Run all math.cos() examples interactively, test degree-to-radian conversions, inspect floating-point tolerances at $90^\circ$, and verify the polar vector converter 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