進口數學計算餘弦我有什麼做一個總體思路,但我的代碼是一個爛攤子,我遇到了一些麻煩用Python寫的算法沒有蟒蛇
cos(x)=1-(x^2)/2!+(x^4)/4!-(x^6)/6!+...
其中x
是在使用while循環的20個項之後計算cos(x)
。到目前爲止,我已經寫了什麼是
x = float(input("Enter a value for x in degrees."))
x = (x*3.14159)/180
num_of_terms = 0
num = 1.0 ##numerator
y = 1.0
cosx = 1.0
while num_of_terms<1:
num_of_terms+=1
cosx = (num/y)
while num_of_terms>=1 and num_of_terms<=20:
num_of_terms+=1
num = num*(x*x)
y = y*num_of_terms*(num_of_terms-1)
if num_of_terms%2==0:
cosx = cosx+(-num/y)
else:
cosx = cosx+(num/y)
print(cosx)
我不知道如何接近我,甚至我到是正確(我知道這是錯的,至少有些地方,所以我不能正確檢查使用math.cos
),但我的主要問題是如何從正面 - >負面切換每個術語。分配規定,我不能使用冪運算符,而之前我試圖做類似
x = float(input("Enter a value for x in degrees."))
x = (x*3.14)/180
num_of_terms = 0
y = 0
z = 1
cosx = ((-1)**(z-1))*((x**z)/(y))
以便符號會切換爲每其他條款。現在我已經(如你所見)
if num_of_terms%2==0:
cosx = cosx+(-num/y)
else:
cosx = cosx+(num/y)
這是不正確的,或者至少我得到的輸出是不正確的。
我應該用y替換num_of_terms嗎? – AxTqka
@AxTqka不,這將是錯誤的。如果你暫時停下來思考這個問題,我相信答案會出現在你的面前。 –