How to Find Cosine in Python
To compute the cosine of an angle using Python, you can utilize the cos() function from the `math` library.
import math
math.cos (x)
Here, "x" represents the angle in radians.
The cos(x) function returns the cosine value of "x".
Understanding the Cosine Function. In trigonometry, the cosine represents the ratio between the side adjacent to the angle (OA) and the hypotenuse (OB). The cosine value is 1 when the angle is 0 degrees and 0 when the angle is 90 degrees.
Example
Example 1
This script calculates the cosine of a 45° angle.
The math.radians() function is used to convert degrees into radians.
import math
x = math.radians (45)
math.cos (x)
The output for the above code is:
0.7071067811865476
Thus, the cosine of a 45° angle (π/4 radians) is approximately 0.7071067811865476.
Example 2
This script calculates the cosine of a 45° angle using π (π ≈ 3.14) to represent radians.
import math
x = math.pi / 4
math.cos (x)
In the "math" library, π is represented as math.pi.
The output for this code is also:
0.7071067811865476
This is the same result as in the previous example, but derived in a different manner.
Note. The cosine function in Python doesn't return an exact zero value for angles of 90° and 270°. Instead, it returns a very small value close to zero. This can be problematic in certain applications. To mitigate this, it's recommended to round the result of `cos(x)` to at least 5 decimal places. In Python, the cosine values for 90° and 270° are not precisely zero.