簡體   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