NumPy: Convert angles from degrees to radians for all elements in a given array
NumPy Mathematics: Exercise-24 with Solution
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.
Python-Numpy Code Editor:
Previous: Write a NumPy program to convert angles from radians to degrees for all elements in a given array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://www.w3resource.com/python-exercises/numpy/python-numpy-math-exercise-24.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics