Taylor series of cosx expansion in Python

105 Views Asked by At

I want to write a function of cos(x) using the Taylor Expansion, but not using the math.factorial function. I defined the factorial of 2i as:

def factorial_two(i):
    if i < 0:
        #Handling negative numbers
        print("Error: can't compute the factorial of a negative number!")
        return None
    elif i == 0:
        #The special case i = 0
        return 1
    else:
        i = i * 2
        #The general case
        fact = 1
        while i > 0:
            fact = fact * i
            i = i - 1
        return fact

Then I defined the approximation of cosine as:

def cosine_approx(x,n):
    sum = 0 
    for i in range(0, n+1):
        sum += ((-1) ** i) * (x**(2*i)/ factorial_two(i))
        return sum

When I run this for any x and any n I always get 1.0 as the result. When I tried the exact same function for cosine_approx(x,n), but instead use the basic math.factorial(2*i) I get the correct results. So the question is, where did I go wrong with by definition? Or am I not using it correctly? Thank you in advance.

1

There are 1 best solutions below

1
SirAmir On

your code has an error you put return sum in the for loop!! so sum always be 1.0 and returend. you should put that out of for loop.

for i in range(0, n+1):
    sum += ((-1) ** i) * (x**(2*i)/ factorial_two(i))
return sum

like that.