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.
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))
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:
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.
If you liked this post, then please share this with your friends and make sure to bookmark this website for more awesome content.