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.
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