简体   繁体   English

正弦的泰勒级数使用函数

[英]Taylor Series for sine using functions

I've created a fatorial function that would help me calculate the taylor expansion of sine.我创建了一个阶乘函数,可以帮助我计算正弦的泰勒展开。 There are no evident mistakes in my code, but the returned value is wrong.我的代码没有明显的错误,但是返回的值是错误的。 That's my code:那是我的代码:

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

You are summing theta in the while-loop and therefore using an adjusted angle for the next elements of the Taylor series.您在 while 循环中对 theta 求和,因此对泰勒级数的下一个元素使用调整后的角度。 Just add a thetas (for the sum) like so (I have taken the liberty to add some performance improvements, no need to recalculate the full factorial, also calculated first elements explicitly and changed the limit check to avoid recalculations of x/y):只需像这样添加一个 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))

this results in这导致

0.984807753125684 0.984807753012208

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

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