Python program to compute sin(x) using Taylor’s series

Hello everyone, welcome to nkcoderz.com. In this article we will going to discuss about python program to compute sin(x) using Taylor’s series.

C program to compute sin(x) using Taylor’s series

Code for python program to compute sin(x) using Taylor’s series

from math import factorial

def sin(x, n):
    x = x % (2 * 3.14)
    sin = 0
    for i in range(n):
        sin += ((-1)**i * x**(2*i+1))/factorial(2*i+1)
    return sin

# Test the function
print(sin(3.14/2, 5)) 

Output

0.9999999999999998

Explanation

The program defines a function sin that takes an angle x in radians and a number of iterations n as arguments. Inside the function, x is first taken modulo 2pi to ensure it falls in the range of [-2pi, 2*pi].

The function then initializes the variable sin to 0, and uses a for loop to compute the sum of the first n terms of the Taylor series for the sine function:

Where x is the angle in radians, and n is the number of iterations. In the for loop, each term of the series is calculated by raising -1 to the power of the index, and multiplying it by the value of x raised to the power of twice the index plus 1, divided by the factorial of twice the index plus 1.

Each term of the series is added to the sin variable, and at the end of the loop sin variable is returned as the approximated sine value.

Python program to find the square root of the given number without a square-root function

Conclusion

If you liked this post, then please share this with your friends and make sure to bookmark this website for more awesome content.


If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment