繁体   English   中英

Python 中 sin(x) 的泰勒级数循环

[英]Taylor Series Loop for sin(x) in Python

我正在 Jupyter Notebook 中的 Python 程序上工作,该程序输出泰勒级数 sin(x) 和 e^x 的总和,并将它们与数学模块的 output 进行比较以进行学校作业。 e^x 部分似乎工作正常,output 和接近模块计算。 但是, sin(x) 部分完全关闭,我不知道为什么。 我确定它必须在我的 series_sum 计算设置中,但我已经盯着它看了好几个小时,没有运气。 如果可以的话请帮忙,非常感谢!

import math

def taylor(func,x,terms=10):
    series_sum=0
    if func=='sin':
        for i in range(terms):
            if(i==10):
                break;
            series_sum=series_sum+(math.pow(-1,i)*math.pow(x,2*i+1))/math.factorial(2*i+1)
            math_value=math.sin(x)
        print("The Taylor series approx is",series_sum,"and the math function value is",math_value)
    else:
        for i in range(terms):
            if(i==10):
                break;
            series_sum=series_sum+math.pow(x,i)/math.factorial(i)
            math_value=math.exp(x)
        print("The Taylor series approx is",series_sum,"and the math function value is",math_value)
func=input("Which function to use sin/exp:")
x=int(input("Enter the value of x: "))
terms=int(input("Enter number of terms: "))
if x>50:
    raise Exception("x should NOT exceed 50")
elif x<-50:
    raise Exception("x should NOT be less than -50")
elif terms>100:
    raise Exception("terms should NOT exceed 100")
elif terms<1:
    raise Exception("terms should NOT be less than 1")
else:
    taylor(func,x,terms)

Sinus 定义在02*PI的范围内,因此要获得更精确的结果,只需在计算 sin Tayloror 级数之前执行x = x % (2 * math.pi)

import math

def sin_taylor(x, terms=10):
    series_sum = 0
    math_value = math.sin(x)
    x = x % (2 * math.pi)
    for i in range(terms):
        series_sum = series_sum + (
            math.pow(-1, i) * math.pow(x, 2 * i + 1) / math.factorial(2 * i + 1)
        )

    print(
        "The Taylor series approx is",
        series_sum,
        "and the math function value is",
        math_value,
    )


sin_taylor(62.3, 10)

印刷:

The Taylor series approx is -0.5072969037125172 and the math function value is -0.5071313157685321

暂无
暂无

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

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