you are here->home->Computer Science->Class 12->sin(x, n) to calculate the value of sin(x) using its Taylor series expansion

sin(x, n) to calculate the value of sin(x) using its Taylor series expansion

- import math
- def fact(n):
- if n<=1:
- return 1
- else:
- return n*fact(n-1)
- n = int(input("How many terms:"))
- x = int(input("Enter the value of x"))
- tot=0;
- for i in range (n+1):
- tot+=(math.pow(-1,i)*math.pow(x,2*i+1))/fact(2*i+1)
- totr=round(tot,5)
- print("The result of sin",'(',x,')','is',totr)

The given program is 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.

**Here's a step-by-step explanation of how the code works:**

- Define a function fact(n) that takes an integer n as input.
- If n is less than or equal to 1, return 1.
- Otherwise, recursively call the fact function with n-1 as the input and multiply the result by n.
- This function calculates the fact of n.
- Prompt the user to enter the number of terms (n) in the Taylor series.
- Prompt the user to enter the value of x.
- Initialize a variable tot to 0, which will store the sum of the terms in the Taylor series.
- Start a loop that iterates n+1 times, with the loop variable i representing the term index.
- For each iteration: Calculate the term using the formula ((-1)^i * x^(2*i+1)) / fact(2*i+1).
- Add the calculated term to the variable tot.
- After the loop, calculate totr by rounding tot to 5 decimal places.
- Print the result as "The result of sin(x) is totr", where x is the user-input value and totr is the rounded approximate value of sin(x).

The code assumes the availability of the math module as it uses the math.pow() function for exponentiation. To execute this code, ensure that you import the math module at the beginning of your script.

- Enter the two input values.
- Click on the Submit button.
- Select the variables from the dropdown list.
- Click on the Finish button or Start button to view the State diagram.
- If you have clicked on the Start button, then use Next and Previous button to view the State diagram.
- Click on the Reset button when the State diagram is completed.