← back

Taylor Series Approximation

#310 · Machine Learning · Easy

⊣ Solve on deep-ml.com

Problem

Implement a Taylor series approximation for a given function around a point a, up to degree n. The Taylor series is: f(x) approx sum_{k=0}^{n} f^(k)(a) / k! * (x - a)^k.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import numpy as np
from math import factorial

def numerical_nth_derivative(f, x: float, n: int, h: float = 1e-5) -> float:
    """Compute the nth derivative of f at x using finite differences."""
    if n == 0:
        return f(x)
    coeffs = np.zeros(n + 1)
    for i in range(n + 1):
        sign = (-1) ** (n - i)
        binom = factorial(n) // (factorial(i) * factorial(n - i))
        coeffs[i] = sign * binom
    result = 0.0
    for i in range(n + 1):
        result += coeffs[i] * f(x + i * h)
    return result / (h ** n)

def taylor_series(f, a: float, x: float, degree: int) -> float:
    result = 0.0
    for k in range(degree + 1):
        dk = numerical_nth_derivative(f, a, k)
        result += dk / factorial(k) * (x - a) ** k
    return result

def taylor_coefficients(f, a: float, degree: int) -> list[float]:
    coeffs = []
    for k in range(degree + 1):
        dk = numerical_nth_derivative(f, a, k)
        coeffs.append(dk / factorial(k))
    return coeffs

Explanation

  1. Compute the nth derivative numerically using forward finite differences with binomial coefficients.
  2. For each term k from 0 to degree, compute f^(k)(a) / k! * (x - a)^k.
  3. Sum all terms to get the Taylor approximation at point x.
  4. The approximation improves with higher degree and is more accurate for x closer to a.

Complexity

  • Time: O(degree^2) function evaluations (each derivative of order k requires k+1 evaluations)
  • Space: O(degree) for storing coefficients