Python Program to Find the Sum of Cosine Series

This is a Python Program to find the sum of cosine series.

Problem Description

The program takes in the the number of terms and finds the sum of cosine series.

Problem Solution

1. Take in the value of x in degrees and the number of terms and store it in separate variables.
2. Pass these values to the cosine function as arguments.
3. Define a cosine function and using a for loop which iterates by 2 steps, first convert degrees to radians.
4. Then use the cosine formula expansion and add each term to the sum variable.
5. Then print the final sum of the cosine expansion.
6. Exit.

Program/Source Code

Here is source code of the Python Program to find the sum of cosine series. The program output is also shown below.

import math
def cosine(x,n):
    cosx = 1
    sign = -1
    for i in range(2, n, 2):
        pi=22/7
        y=x*(pi/180)
        cosx = cosx + (sign*(y**i))/math.factorial(i)
        sign = -sign
    return cosx
x=int(input("Enter the value of x in degrees:"))
n=int(input("Enter the number of terms:"))
print(round(cosine(x,n),2))
Program Explanation

1. User must enter the value of x in degrees and the number of terms and store it in separate variables.
2. These values are passed to the cosine functions as arguments.
3. A cosine function is defined and a for loop is used convert degrees to radians and find the value of each term using the sine expansion formula.
4. Each term is added the sum variable.
5. This continues till the number of terms is equal to the number given by the user.
6. The total sum is printed.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Enter the value of x in degrees:0
Enter the number of terms:10
1.0
 
Case 2:
Enter the value of x in degrees:75
Enter the number of terms:15
0.26

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

Note: Join free Sanfoundry classes at Telegram or Youtube

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.