Monday 28 December 2020

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.

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

No comments:

Post a Comment