簡體   English   中英

誰能說明為什么使用泰勒級數展開計算 sin(x) 值的給定代碼不能正常工作?

[英]Can anyone show why the given code to calculate the value of sin(x) using Taylor series expansion not working properly?

這是我試過的代碼,它不能正常工作,我不知道這個問題

import math as m
def sinse(x,n):
    sume=0
    for i in range(n+1):
        sume+=(m.pow(-1,i)*m.pow(x,2*i+1)/m.factorial(2*i+1))
        return sume
n=int(input('Enter the value of n:'))
x=int(input('enter the value of X:'))
print(sinse(x,n))

如果這不是正確的代碼,請在答案中添加任何其他代碼

return sume行打破了 for 循環。 我不確定您的公式的准確性,但我認為將該行取消縮進 1(因此它發生在 for 循環之后但在函數內部)應該可以使其工作。

固定縮進會給出以下結果:

import math as m
def sinse(x,n):
    sume=0
    for i in range(n+1):
        sume+=(m.pow(-1,i)*m.pow(x,2*i+1)/m.factorial(2*i+1))
    return sume
n=int(input('Enter the value of n:'))
x=int(input('enter the value of X:'))
print(sinse(x,n))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM