# cat demo1.py
import numpy as np
import math
def f(x):
return np.exp(x)
def derivative(x):
return f(x)
def taylor_expand(f, x0, n, x):
r = f(x0)
for i in range(1, n + 1):
r += derivative(x0) * ((x - x0) ** i) / math.factorial(i)
return r
x = 1
x0 = 5
n = 40
r1 = taylor_expand(f, x0, n, x)
r2 = np.exp(x)
print("taylor-expand:", r1)
print("origin-result:", r2)
print("Rn(x) Estimation:", (x0 - x) ** (n + 1) * np.exp(x0) / math.factorial(n + 1))
print("diff=", (r2 - r1))
"""
目的: 用 e^x 在 x0=5处的展开,估算e^x在(x=1)处的数据, 并计算估计误差Rn(x)
taylor-expand: 2.718281828459021
origin-result: 2.718281828459045
Rn(x) Estimation: 2.1453745731609467e-23
diff= 2.398081733190338e-14
疑问: Rn(x)误差估计是 10^(-23) 可是实际上 diff是10^(-14) , 这个差距有点大,why
猜测: 1. 累加计算过程有误差 2. np计算本身有误差 3.程序逻辑有问题
"""
# cat demo2.py
import mpmath
# 设置精度(位数)
mpmath.mp.dps = 50 # 设置为 50 位小数
# 定义函数 f(x) = exp(x)
def f(x):
return mpmath.exp(x)
def derivative(x):
return f(x)
# 计算阶乘
def factorial(n):
return mpmath.factorial(n)
# 泰勒展开函数
def taylor_expand(f, x0, n, x):
r = f(x0)
for i in range(1, n + 1):
r += derivative(x0) * ((x - x0) ** i) / factorial(i)
return r
x = mpmath.mpf(1)
x0 = mpmath.mpf(5)
n = 40
# 计算泰勒展开
r1 = taylor_expand(f, x0, n, x)
r2 = mpmath.exp(x)
r3 = ((x0 - x) ** (n + 1)) * mpmath.exp(x0) / mpmath.factorial(n + 1)
print("taylor-expand:", r1)
print("origin-result:", r2)
print("Rn(x) Estimation:", r3)
print("diff=", (r2 - r1))
"""
taylor-expand: 2.7182818284590452353603070560849832858516189537689
origin-result: 2.7182818284590452353602874713526624977572470937
Rn(x) Estimation: 2.1453745731609467149330950275147177017147805869338e-23
diff= -1.958473232078809437186006894647201943730120045111e-23
这里数量级非常接近了10^(-23)次方误差是一样的
"""