"""Compare Taylor polynomials and calculate a local quadratic step."""
from fractions import Fraction as F
import json
from math import exp,factorial,sin
import platform
import numpy as np
def sin_polynomial(x, degree):
return sum((-1)**((k-1)//2)*x**k/factorial(k) for k in range(1,degree+1,2))
def exp_polynomial(x, degree):
return sum(x**k/factorial(k) for k in range(degree+1))
def main():
cases = []
def check(name,inputs,expected,actual,operation):
assert expected == actual,(name,expected,actual)
cases.append(dict(name=name,input=inputs,operation=operation,expected=expected,actual=actual,passed=True))
degrees = [1,3,5]
x = F(1,2)
estimates = [sin_polynomial(x,d) for d in degrees]
check("sin_degrees_one_three_five", {"x":"1/2","degrees":degrees}, ["1/2","23/48","1841/3840"],
list(map(str, estimates)), "sum the signed exact rational terms")
actual = sin(float(x))
errors = [abs(float(v)-actual) for v in estimates]
check("sin_alternating_error_bound", {"x":"1/2","degrees":degrees}, [True]*3,
[error<=float(x**(d+2)/factorial(d+2)) for error,d in zip(errors,degrees,strict=True)],
"compare each absolute error with the first omitted term")
check("sin_point_one_linear", {"x":.1,"digits":6}, [0.1,0.099833,0.000167],
[float(sin_polynomial(F(1,10),1)),round(sin(.1),6),round(.1-sin(.1),6)], "compare to the tangent")
value = exp_polynomial(F(1,2),3)
check("exponential_coefficients", {"x":"1/2","degree":3}, ["79/48",True],
[str(value),0<exp(.5)-float(value)<.005], "evaluate the first four exponential terms")
center,offset = 3.,.25
exact = (center+offset)**2
first = center**2+2*center*offset
second = first+offset**2
check("linear_and_quadratic_at_center", [center,offset], [10.5,10.5625,10.5625],
[first,second,exact], "compare degree one, degree two and the true quadratic")
hessian = np.array([[4.,0.],[0.,2.]])
point = np.array([2.,-1.])
minimum = np.array([1.,1.])
gradient = hessian@(point-minimum)
newton = point + np.linalg.solve(hessian,-gradient)
descent = point - .125*gradient
check("positive_definite_hessian_step", {"point":point.tolist(),"H":hessian.tolist(),"eta":.125},
[[1.,1.],[1.5,-.5]], [newton.tolist(),descent.tolist()], "solve for the Newton step and compare a gradient step")
flat = lambda u: exp(-1/u**2)
check("smooth_flat_function_nonzero_away", .5, True, flat(.5)>0, "evaluate the flat-function example away from the center")
gradient_sum, curvature_sum, penalty = -3.,5.,1.
weight = -gradient_sum/(curvature_sum+penalty)
objective = lambda w: gradient_sum*w+(curvature_sum+penalty)*w*w/2
check("regularized_tree_leaf_weight", {"G":gradient_sum,"H":curvature_sum,"lambda":penalty},
[.5,-.75,True], [weight,objective(weight),objective(weight)<min(objective(weight-.25),objective(weight+.25))],
"minimize a scalar second-order tree-leaf objective")
print(json.dumps(dict(version=platform.python_version(),library_versions={"numpy":np.__version__},cases=cases)))
if __name__ == "__main__":
main()
本例需在 Windows、Python 3.12.14。numpy 2.5.4。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12.14。numpy 2.5.4。
入口文件:projects/ai-math-taylor-series-lab/taylor-lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
taylor-lab.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14。numpy 2.5.4。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联54章) · 含当前章节或实例 · mbskycom202612a33.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a84.zip