Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Get the Trigonometric cosine of an array of angles given in degrees with Python
To find the trigonometric cosine of an array of angles given in degrees, use the numpy.cos() method in Python NumPy. Since numpy.cos() expects angles in radians, you need to convert degrees to radians by multiplying by ?/180.
Syntax
numpy.cos(x, out=None, where=True)
Parameters
The parameters of numpy.cos() are:
- x - Input array of angles in radians
- out - Optional output array where results are stored
- where - Optional condition to apply the function selectively
Converting Degrees to Radians
Since cosine function expects radians, multiply degrees by ?/180 ?
import numpy as np
# Array of angles in degrees
angles_degrees = np.array([0, 30, 45, 60, 90, 180])
print("Angles in degrees:", angles_degrees)
# Convert to radians and find cosine
cosine_values = np.cos(angles_degrees * np.pi / 180)
print("Cosine values:", cosine_values)
Angles in degrees: [ 0 30 45 60 90 180] Cosine values: [ 1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01 6.12323400e-17 -1.00000000e+00]
Using numpy.radians() for Conversion
Alternatively, use numpy.radians() for cleaner degree-to-radian conversion ?
import numpy as np
angles_degrees = np.array([0, 30, 45, 60, 90, 180])
# Using np.radians() for conversion
cosine_values = np.cos(np.radians(angles_degrees))
print("Angles in degrees:", angles_degrees)
print("Cosine values:", cosine_values)
# Rounded for better readability
print("Rounded cosine values:", np.round(cosine_values, 3))
Angles in degrees: [ 0 30 45 60 90 180] Cosine values: [ 1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01 6.12323400e-17 -1.00000000e+00] Rounded cosine values: [ 1. 0.866 0.707 0.5 0. -1. ]
Working with 2D Arrays
The function also works with multi-dimensional arrays ?
import numpy as np
# 2D array of angles in degrees
angles_2d = np.array([[0, 30, 45],
[60, 90, 180]])
print("2D array of angles:")
print(angles_2d)
cosine_2d = np.cos(np.radians(angles_2d))
print("\nCosine values:")
print(np.round(cosine_2d, 3))
2D array of angles: [[ 0 30 45] [ 60 90 180]] Cosine values: [[ 1. 0.866 0.707] [ 0.5 0. -1. ]]
Key Points
-
numpy.cos()expects angles in radians, not degrees - Convert degrees to radians using
* np.pi / 180ornp.radians() - The function works with arrays of any shape
- Very small values near zero (like 6.12e-17) represent floating-point precision limits
Conclusion
Use np.cos(np.radians(degrees)) to find cosine values of angles in degrees. The numpy.radians() function provides a cleaner way to convert degrees to radians before applying the cosine function.
Advertisements
