Kodeclik Blog

math.cos() in Python

Recall that the cosine of an angle is defined as the adjacent side (adjacent to the angle) divided by the hypotenuse in a right-angled triangle. It is well known that the cosine of zero is 1 and the cosine of 90 degrees (which is pi/2 radians) is 0. The math.cos() is a handy function in Python to compute these trigonometric ratios.
Consider the following program:
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 cos() 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.)
The output is:
The second line’s output shows floating point errors in the math module, i.e., the output is a number quite close to zero but not exactly zero.

Computing the cosine function using Taylor series approximation

If you did not have access to the cos() function you can approximate the cos 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 cosine 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 cos(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 15 terms in the cosine function expansion to approximate the value of cos(). And you can see that the result is not exactly 0.0 (just like the case of the Math.cos() 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.cos() 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.cos() function, you should checkout our blogposts on the math.sin() and math.tan() functions!
Now that you have mastered the math.cos() function, checkout the math.ceil() and math.floor() functions! Also learn about the math domain error in Python and how to fix it!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2024. All rights reserved.