NumPy: Convert angles from radians to degrees for all elements in a given array
23. Convert Radians to Degrees
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.
For more Practice: Solve these Related Problems:
- Implement a function that converts an array of radian values to degrees using np.degrees.
- Test the function on both positive and negative radian values and compare with the manual conversion formula.
- Create a solution that applies the conversion to a multi-dimensional array and verifies that the output shape is preserved.
- Compare the np.degrees output with a vectorized multiplication by 180/π for a set of test values.
Python-Numpy Code Editor:
Previous: Write a NumPy program to calculate inverse sine, inverse cosine, and inverse tangent for all elements in a given array.Next: Write a NumPy program to convert angles from degrees to radians for all elements in a given array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics