w3resource

NumPy: Convert angles from radians to degrees for all elements in a given array


Write a NumPy program to convert angles from radians to degrees for all elements in a given array.

Sample Input: [-np.pi, -np.pi/2, np.pi/2, np.pi]

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating an array of angles in radians: [-π, -π/2, π/2, π]
x = np.array([-np.pi, -np.pi/2, np.pi/2, np.pi])

# Converting angles from radians to degrees using np.degrees()
r1 = np.degrees(x)

# Converting angles from radians to degrees using np.rad2deg()
r2 = np.rad2deg(x)

# Checking if the results from np.degrees() and np.rad2deg() are equivalent
assert np.array_equiv(r1, r2)

# Printing the converted angles in degrees
print(r1) 

Sample Output:

[-180.  -90.   90.  180.]

Explanation:

x = np.array([-np.pi, -np.pi/2, np.pi/2, np.pi]): This code defines a numpy array x containing four angles in radians: -π, -π/2, π/2, and π.

r1 = np.degrees(x): The np.degrees() function is used to convert the angles in x to degrees, resulting in a new array r1 where each angle in x has been converted to its equivalent in degrees.

r2 = np.rad2deg(x): This code is used to perform the same conversion from radians to degrees, resulting in a new array r2.

assert np.array_equiv(r1, r2): Finally, the np.array_equiv() function is used to check if the two arrays r1 and r2 have the same values. If the arrays are equivalent, the assertion will pass without an error.

Python-Numpy Code Editor: