使用泰勒级数逼近 sin

问题描述

我正在尝试使用泰勒级数而不使用阶乘来计算 sin(x)

import math,time
import matplotlib.pyplot as plot

def sin3(x,i=30):
    x %= 2 * math.pi
    n = 0
    dn = x**2 / 2
    for c in range(4,2 * i + 4,2):
        n += dn
        dn *= -x**2 / ((c + 1) * (c + 2))
    return x - n

def draw_graph(start = -800,end = 800):
    y = [sin3(i/100) for i in range(start,end)]
    x = [i/100 for i in range(start,end)]

    y2 = [math.sin(i/100) for i in range(start,end)]
    x2 = [i/100 for i in range(start,end)]

    plot.fill_between(x,y,facecolor="none",edgecolor="red",lw=0.7)
    plot.fill_between(x2,y2,edgecolor="blue",lw=0.7)
    plot.show()

当您运行 draw_graph 函数时,它使用 matplotlib 绘制图形,红线是我的 sin3 函数的输出,蓝线是 math.sin 的正确输出方法。

enter image description here

正如您所看到的曲线不太正确,它不够高或不够低(似乎在 0.5 处达到峰值),并且还有奇怪的行为,它在 0.25 附近生成一个小峰值然后再次下降。如何调整我的函数以匹配 math.sin 的正确输出?

解决方法

sin(x) 的方程错误,而且循环不变量也搞砸了。

sin(x) 的公式是 x/1! - x^3/3! + x^5/5! - x^7/7!...,所以我真的不知道您为什么要将 dn 初始化为涉及 x^2 的内容。

你还想问自己:我的循环不变式是什么?当我到达循环开始时 dn 的值是多少。从您更新 dn 的方式可以清楚地看出,您希望它涉及 x^i / i!。然而在循环的第一次迭代中,i=4,但 dn 涉及 x^2

这是你想写的:

def sin3(x,i=30):
    x %= 2 * math.pi
    n = 0
    dn = x
    for c in range(1,2 * i + 4,2):
        n += dn
        dn *= -x**2 / ((c + 1) * (c + 2))
    return n

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...