【问题标题】:Taylor Series for sine using functions正弦使用函数的泰勒级数
【发布时间】:2021-02-19 04:53:28
【问题描述】:

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

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

【问题讨论】:

  • 我没有看到任何明显的错误。结果有多差?你确定你的输入是正确的吗?
  • 错误出现在小数点后第二位。显然,输入是正确的。
  • 输入输出是什么?
  • 例如,如果输入是 seno(80),预期输出应该是 0.98480775301(计算器),但函数返回 0.9486468804696462

标签: python python-3.x taylor-series


【解决方案1】:

您在 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

【讨论】:

    猜你喜欢
    • 2017-12-02
    • 2021-07-10
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    相关资源
    最近更新 更多