27.3_泰勒展开的实现

27.3 泰勒展开的实现

下面根据式子27.3来实现sin函数。为了计算阶乘,我们需要使用Python的math模块中的math-factorial函数。

steps/step27.py

import math   
def my_sin(x, threshold=0.0001): y = 0 for i in range(100000): c  $=$  (-1) \*\*i/math.factorial(2\*i+1) t  $=$  c\*x\*\* (2\*i+1) y  $=$  y+t if abs(t.data) < threshold: break return y

上面的代码基于式子27.3实现,for语句中的t是第i次要添加的项。代码中的threshold是阈值,当t的绝对值低于阈值时,程序退出for循环。代码通过threshold控制近似精度(threshold越小,近似精度越高)。

接下来使用上面实现的my_sin函数进行计算。

steps/step27.py

$\begin{array}{rl} & {\mathrm{x} = \mathrm{Variable}(\mathrm{np.array}(\mathrm{np.pi / 4}))}\\ & {\mathrm{y} = \mathrm{my\_sin}(\mathrm{x})}\\ & {\mathrm{y\_backward()}}\\ & {\mathrm{print(y.data)}}\\ & {\mathrm{print(x.grad)}} \end{array}$

运行结果

0.7071064695751781  
0.7071032148228457

这个结果与本步骤最开始实现的sin函数的计算结果基本相同。误差很小,可以忽略。降低threshold的值可以进一步缩小误差。

从理论上来说,泰勒展开的阈值(threshold)越小,近似精度越高。但计算机在计算的过程中会出现精度丢失和舍入误差等情况,所以结果并不一定与理论值相符。