繁体   English   中英

正弦的泰勒级数使用函数

[英]Taylor Series for sine using functions

我创建了一个阶乘函数,可以帮助我计算正弦的泰勒展开。 我的代码没有明显的错误,但是返回的值是错误的。 那是我的代码:

PI = 3.14159265358979323846

def fatorial(n):

    fatorial = 1
    for i in range(1,n+1,1):
        fatorial = fatorial * i
    return fatorial 

def seno(theta):
   
    n = 1
    k = 3
    eps = 10**-10
    theta = (theta*PI)/180
    x = ((-1)**n)*((theta)**k)
    y = fatorial(k)
    while x/y > eps or x/y < -eps:
        theta = theta + (x/y)
        n = n + 1
        k = k + 2
        x = ((-1)**n) * ((theta)**k)
        y = fatorial(k)
    return theta

您在 while 循环中对 theta 求和,因此对泰勒级数的下一个元素使用调整后的角度。 只需像这样添加一个 thetas(用于总和)(我冒昧地添加了一些性能改进,无需重新计算全阶乘,还明确计算了第一个元素并更改了限制检查以避免重新计算 x/y):

import math

PI = 3.14159265358979323846

def fatorial(n):
    fatorial = 1
    for i in range(1,n+1,1):
        fatorial = fatorial * i
    return fatorial 

def seno(theta): 
    n = 1
    k = 3
    #eps = 10**-10
    theta = (theta*PI)/180
    thetas = theta # <- added this
    x = -theta*theta*theta
    y = 6
    #while x/y > eps or x/y < -eps:
    while k < 14:
        thetas = thetas + (x/y) # sum thetas
        n = n + 1
        k = k + 2
        #x = ((-1)**n) * ((theta)**k)
        x = ((-1)**(n%2)) * ((theta)**k) # but use the original value for the series
        #y = fatorial(k)
        y *= k * (k-1)
    return thetas # return the sum

if __name__ == '__main__':
    print(seno(80), math.sin(8*PI/18))

这导致

0.984807753125684 0.984807753012208

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM