简体   繁体   中英

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. I use enthought canopy IDE, where have I gone wrong?

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. 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.

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").

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. The usual trick is to keep the last value of sum, and stop iterating when it doesn't change.

NB2: You could optimize your program by avoiding to recompute y**(2*i)) and 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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