进口数学计算余弦我有什么做一个总体思路,但我的代码是一个烂摊子,我遇到了一些麻烦用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不,这将是错误的。如果你暂时停下来思考这个问题,我相信答案会出现在你的面前。 –