Tuesday, 16 July 2019

12th Prog-6 Write a Python function sin(x, n) to calculate the value of sin(x) using its Taylor series expansion up to n terms. Compare the values of sin(x) for different values of n with the correct value

Algorithm:
Input:
1. x   2. n(number of terms
output: 
sin(x,n)
Method
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 sine function as arguments.
3. Define a sine function and using a for loop, first convert degrees to radians.
4. Then use the sine formula expansion and add each term to the sum variable.
5. Then print the final sum of the expansion.
6. Exit.

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

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 sine functions as arguments.
3. A sine 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.

Output
1. Enter the value of x in degrees:30
Enter the number of terms:10
0.5
2. Enter the value of x in degrees:45
Enter the number of terms:15
0.71

C

No comments:

Post a Comment