w3resource

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

NumPy Mathematics: Exercise-23 with Solution

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:

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-math-exercise-23.php