Recall that the sine of an angle is defined as the opposite side (opposite to the angle) divided by the hypotenuse in a right-angled triangle. It is well known that the sine of zero is zero and the sine of 90 degrees (which is pi/2 radians) is 1. The Math.sin() is a handy function in Python to compute these trigonometric ratios. Consider the following program:
The output is:
Note that in the second line we are careful to convert degrees to radians (by scaling by pi/180) before passing the result to the sin() function. (In the first line, we know that 0 degrees is the same as 0 radians, so we do not need to be so careful.)
Computing the sine function using Taylor series approximation
If you did not have access to the sin() function you can approximate the sin function by using a Taylor series expansion (expanded around 0) as shown in the below function:
The above function takes two inputs, viz. Theta the angle for which we wish to compute the sine() and n, the number of terms. Inside the function, we first convert the angle to radians and then use a for loop to add up terms according to the Taylor expansion for sin(theta). Even though the Taylor’s series is infinite, we are approximating it here with a finite number of terms.
Now we can use this function like so:
The output will be:
As you can see we are using five terms in the sine function expansion to approximate the value of sin(). And you can see that the result is not exactly 1.0. (as produced by the Math.sin() function). If we increase the number of terms we will get increasingly more accurate results. Here is some code to explore this:
The output will be:
As you can see, after a few terms we see the series converging to the desired value.
In conclusion, you can use the math.sin() function which is a built-in function in the math module of Python or you can construct your own approximation using Taylor series.
If you liked learning about the math.sin() function, you should checkout our blogposts on the math.cos() and math.tan() functions!
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.