简体   繁体   English

余弦x的泰勒级数在运行时使用python给出逻辑错误

[英]Taylor series for cosine x gives logical error at runtime using python

The code compiles but gives a wrong output. 代码可以编译,但是输出错误。 For example, when I input a value of 45, I get an output of 1.0. 例如,当我输入值45时,输出为1.0。 I use enthought canopy IDE, where have I gone wrong? 我使用有思想的机盖IDE,哪里出了问题?

import math
x = int(raw_input("Enter the size of the angle : ")) 
y = (x*math.pi)/180

# my factorial function
def factorial(n):
    if n == 0 or n == 1:
     return 1
    else:
     return n * factorial(n - 1)
def cos(x): 
    for i in range (9):
     sum = 0
     sum += ((-1)**(i)) * (y **(2* i))/factorial((2*i))
    return sum      

print cos(x)
print y # I wanted to be sure my conversion to radian is  right                

在每个循环中将总和设置回零: sum=0应该在for循环之前,而不是在其中。

Like Chris said, sum=0 should be before the for loop. 就像克里斯说的那样, sum=0应该在for循环之前。 Here's a cleaner code: 这是一个更干净的代码:

def cos(x):
    return sum(((-1)**(i)) * (y **(2* i))/factorial((2*i)) for i in range(9))

The problem is that your program uses integers instead of floating point numbers. 问题在于您的程序使用整数而不是浮点数。 Also, the variable sum should be initialized before the loop. 另外,变量sum应该在循环之前初始化。

import math
x = float(raw_input("Enter the size of the angle : ")) 
y = (x*math.pi)/180.0

#my factorial function
def factorial(n):
    if n == 0 or n == 1:
      return 1
    else:
      return n * factorial(n - 1)
def cos(x): 
  sum = 0.0
  for i in range (9):
    sum += ((-1)**(i)) * (y **(2*i))/factorial((2*i))
  return sum      
print cos(x)
print y

This will work even if type "45" for the angle (without the ".0"). 即使角度输入为“ 45”(不带“ .0”),该设置也将起作用。

NB The higher the value of angle, the longer it takes for the serie to converge (ie give the right answer). 注意:角度值越高,意甲收敛的时间越长(即给出正确的答案)。 Since you only iterate 9 times, it can give inaccurate answers for large values of angle. 由于仅迭代9次,因此对于大角度值,它可能会给出不正确的答案。 The usual trick is to keep the last value of sum, and stop iterating when it doesn't change. 通常的技巧是保留sum的最后一个值,并在其不变时停止迭代。

NB2: You could optimize your program by avoiding to recompute y**(2*i)) and factorial(2*i) . NB2:您可以通过避免重新计算y**(2*i))factorial(2*i)来优化程序。 You could keep the previous values, for example, if you computed the factorial of 8, just multiply by 9 and by 10 to get factorial of 10. In the same way, if you computed y**10 , just multiply it by y*y to get y**12 . 您可以保留先前的值,例如,如果您计算了8的阶乘,只需乘以9和10即可得到10的阶乘。以同样的方式,如果您计算y**10 ,只需将其乘以y*y得到y**12

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

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