Part of the series

Several example codes

~1 min read • Updated Oct 13, 2025

Program Overview

This Python program reads a value x (in degrees) and a number n of terms, and computes an approximation of cos(x) using the Maclaurin series:
cos(x) ≈ ∑ [(-1)^k · x^(2k) / (2k)!] for k from 0 to n


Python Code:


import math

def cosine_maclaurin(x: float, n: int) -> float:
    total = 0.0
    for k in range(n + 1):
        term = ((-1) ** k) * (x ** (2 * k)) / math.factorial(2 * k)
        total += term
    return total

# Read inputs from user
x_deg = float(input("Enter x (in degrees): "))
n = int(input("Enter number of terms: "))

x_rad = math.radians(x_deg)
approx = cosine_maclaurin(x_rad, n)
actual = math.cos(x_rad)

print(f"Approximation of cos({x_deg}) with {n} terms: {approx:.6f}")
print(f"Actual value using math.cos: {actual:.6f}")

Sample Output (input: x = 60, n = 5):


Approximation of cos(60.0) with 5 terms: 0.500000  
Actual value using math.cos: 0.500000

Written & researched by Dr. Shahin Siami