w3resource

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


24. Convert Degrees to Radians

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

Sample Input: Input: [-180., -90., 90., 180.]

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating an array of angles in degrees: [-180, -90, 90, 180]
x = np.array([-180., -90., 90., 180.])

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

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

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

# Printing the converted angles in radians
print(r1) 

Sample Output:

[-3.14159265 -1.57079633  1.57079633  3.14159265]

Explanation:

x = np.array([-180., -90., 90., 180.]): This code defines a numpy array x containing the angles in degrees represented in floating-point format.

r1 = np.radians(x): The np.radians(x) function takes an input array x that contains angles in degrees and returns an array of the same shape with the corresponding angles in radians. The result is stored in r1.

r2 = np.deg2rad(x): The np.deg2rad(x) function also performs the same conversion but is an alternative function name for np.radians().The result is stored in r2.

np.array_equiv(r1, r2): Finally, the np.array_equiv() function is used to verify that r1 and r2 have the same values, which should always be true since they represent the same conversion.


For more Practice: Solve these Related Problems:

  • Implement a function that converts an array of degree values to radians using np.radians.
  • Test the conversion on arrays with extreme values and verify the accuracy of the results.
  • Create a solution that handles both 1D and 2D arrays, ensuring the output shape matches the input.
  • Compare the results of np.radians with a manual conversion (multiplying by π/180) to validate precision.

Go to:


PREV : Convert Radians to Degrees
NEXT : Hyperbolic Trigonometric Functions

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.