Find the Taylor series approximations
Автор: Zhanswjx • Сентябрь 20, 2026 • Задача • 399 Слов (2 Страниц) • 27 Просмотры
Use zero- through fourth-order Taylor series expansions to predict f(2.5) for f(x) = lnx using a base point at x = 1. Compute the true percent relative error E, for each approximation.
import math
# task info: x = 2.5 and x0 = 1
def func(x):
return math.log(x)
def nth_derivative(func, x, n, h):
"""
Approximate the nth derivative using central differences.
"""
if n == 0:
return func(x)
elif n == 1:
return (func(x + h) - func(x - h)) / (2 * h)
else:
# Recursive differentiation
return (nth_derivative(func, x + h, n - 1, h) -
nth_derivative(func, x - h, n - 1, h)) / (2 * h)
# Print derivatives from 0-th to 4-th order
for i in range(5):
print(i, "-th order derivative \t",
nth_derivative(func, x=1.0, n=i, h=0.001))
def taylor_series(func, x0, order, x_value):
# order - Taylor polynomial degree
if not callable(func):
raise TypeError("func must be a callable function.")
if not isinstance(order, int) or order < 0:
raise ValueError("order must be a non-negative integer.")
approx = 0.0
for n in range(order + 1):
# Compute nth derivative at x0 using numerical differentiation
derivative = nth_derivative(func, x0, n, h=0.001)
approx += (derivative / math.factorial(n)) * (x_value - x0) ** n
return approx
print()
print("Solution:")
x0 = 1
x_value = 2.5
...