Write a program to compute cosine of x. The user should supply x and a positive integer n. We compute the cosine of x using the series and the computation should use all terms in the series up through the term involving xn cos x = 1 - x2/2! + x4/4! - x6/6! .....

Source Code

x = int(input("Enter the value of x: "))
n = int(input("Enter the value of n: "))
sign=-1
fact=1
i=2
sum=0
while i<=n:
    p=1
    fact=1
    for j in range(1,i+1):
        p = p*x
        fact = fact*j
    sum= sum + sign* p/fact
    sign = -1*sign
    i = i+2
print("cos(",x,") =",1+sum)

Output

Enter the value of x: 4
Enter the value of n: 3
cos( 4 ) = -7.0