[英]Approximating sin using the Taylor series
我正在嘗試使用泰勒級數計算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, facecolor="none", edgecolor="blue", lw=0.7)
plot.show()
When you run the draw_graph
function it uses matplotlib to draw a graph, the redline is the output from my sin3
function, and the blue line is the correct output from the math.sin
method.
正如您所看到的曲線不太正確,它不夠高或不夠低(似乎在 0.5 處達到峰值),並且還具有奇怪的行為,它在 0.25 附近產生一個小峰值,然后再次下降。 如何調整我的 function 以匹配 math.sin 的正確 output?
你有錯誤的 sin(x) 方程,你也有一個混亂的循環不變量。
sin(x)
的公式是x/1. - x^3/3. + x^5/5. - x^7/7!...
x/1. - x^3/3. + x^5/5. - x^7/7!...
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.