Lesson 17 of 18

Maclaurin Series for cos(x)

Maclaurin Series for cos(x)\cos(x)

The Maclaurin series is a Taylor series centred at x=0x = 0. For cosine:

cos(x)=k=0(1)k(2k)!x2k=1x22!+x44!x66!+\cos(x) = \sum_{k=0}^{\infty} \frac{(-1)^k}{(2k)!} x^{2k} = 1 - \frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{6!} + \cdots

This series converges for all real xx.

Building Terms Iteratively

Computing each term from scratch (with a factorial and power) is slow. Instead, use the recurrence:

tk+1=tkx2(2k+1)(2k+2)t_{k+1} = t_k \cdot \frac{-x^2}{(2k+1)(2k+2)}

Starting with t0=1t_0 = 1:

double maclaurin_cos(double x, int terms) {
    double sum = 0.0, term = 1.0;
    for (int k = 0; k < terms; k++) {
        sum += term;
        term *= -x * x / ((2.0*k + 1) * (2.0*k + 2));
    }
    return sum;
}

Accuracy vs. Terms

Termscos(π)\cos(\pi) approximationError
31.2337-1.233723%
50.9997-0.99970.03%
101.0000-1.0000109\approx 10^{-9}

Key Values

cos(0)     = 1
cos(π/2)   = 0
cos(π)     = -1
cos(2π)    = 1

Your Task

Implement double maclaurin_cos(double x, int terms) using the iterative term recurrence.

TCC compiler loading...
Loading...
Click "Run" to execute your code.