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 sines of an array of angles given in degrees in Python
To get the trigonometric sines of an array of angles given in degrees, use the numpy.sin() method in Python NumPy. The method returns the sine of each element of the input array. Since numpy.sin() expects angles in radians, we must convert degrees to radians by multiplying by ?/180.
Syntax
numpy.sin(x, out=None, where=True)
Parameters
The function accepts the following parameters:
- x − Input array of angles in radians
- out − Optional output array where results are stored
- where − Optional condition to control where calculation is performed
Example
Let's calculate the sine values for common angles: 0°, 30°, 45°, 60°, 90°, and 180° −
import numpy as np
# Array of angles in degrees
angles_deg = np.array([0., 30., 45., 60., 90., 180.])
print("Angles in degrees:")
print(angles_deg)
# Convert degrees to radians and calculate sine
angles_rad = angles_deg * np.pi / 180
sine_values = np.sin(angles_rad)
print("\nSine values:")
print(sine_values)
# Display results in a formatted way
print("\nAngle (degrees) -> Sine value:")
for deg, sin_val in zip(angles_deg, sine_values):
print(f"{deg:3.0f}° -> {sin_val:.6f}")
Angles in degrees: [ 0. 30. 45. 60. 90. 180.] Sine values: [0.00000000e+00 5.00000000e-01 7.07106781e-01 8.66025404e-01 1.00000000e+00 1.22464680e-16] Angle (degrees) -> Sine value: 0° -> 0.000000 30° -> 0.500000 45° -> 0.707107 60° -> 0.866025 90° -> 1.000000 180° -> 0.000000
Key Points
- Always convert degrees to radians using
degrees * np.pi / 180 - The sine of 180° appears as a very small number (~1.22e-16) instead of exactly 0 due to floating-point precision
- Common sine values: sin(30°) = 0.5, sin(45°) ? 0.707, sin(60°) ? 0.866, sin(90°) = 1
Using numpy.deg2rad() for Conversion
NumPy provides a convenient function for degree-to-radian conversion −
import numpy as np
angles_deg = np.array([0., 30., 45., 60., 90., 180.])
# Using numpy.deg2rad() for conversion
sine_values = np.sin(np.deg2rad(angles_deg))
print("Using np.deg2rad():")
print(sine_values)
Using np.deg2rad(): [0.00000000e+00 5.00000000e-01 7.07106781e-01 8.66025404e-01 1.00000000e+00 1.22464680e-16]
Conclusion
Use numpy.sin() with degree-to-radian conversion to calculate trigonometric sines. The np.deg2rad() function provides a cleaner alternative to manual conversion using ?/180.
Advertisements
