How to convert radians to degrees and vice versa in python ?

June 18, 2019    /    Viewed: 3153    /    Comments: 0    /    Edit


Examples of how to convert radians to degrees and vice versa in python:

Convert radians to degrees using the math module

A first solution is to use the python module math, example:

>>> import math
>>> math.radians(90)
1.5707963267948966
>>> math.pi / 2.0
1.5707963267948966
>>> math.radians(180)
3.141592653589793

Conversion radian -> degrees:

>>> math.degrees(math.pi/2.0)
90.0
>>> math.degrees(math.pi)
180.0

Convert radians to degrees using numpy

Another solution is to use the numpy functions radians and degrees. The advantage of those functions is that a list or a matrix can be passed as an argument.

An example using a number:

>>> import numpy as np
>>> np.radians(90)
1.5707963267948966
>>> np.pi / 2.0
1.5707963267948966
>>> np.radians(180)
3.1415926535897931

Converting radians to degrees:

>>> x = np.pi / 2.0
>>> x
1.5707963267948966
>>> np.degrees(x)
90.0
>>> np.degrees(np.pi)
180.0

An example using a list:

>>> l = [0,45,90,180,360]
>>> np.radians(l)
array([ 0.        ,  0.78539816,  1.57079633,  3.14159265,  6.28318531])
>>> l = [ 0.        ,  0.78539816,  1.57079633,  3.14159265,  6.28318531]
>>> np.degrees(l)
array([   0.        ,   44.99999981,   90.00000018,  179.99999979, 360.00000016])

An example using an array:

>>> A = np.array(([0,45,90,180,360]))
>>> A
array([  0,  45,  90, 180, 360])
>>> A.shape
(5,)
>>> B = np.radians(A)
>>> B
array([ 0.        ,  0.78539816,  1.57079633,  3.14159265,  6.28318531])
>>> C = np.degrees(B)
>>> C
array([   0.,   45.,   90.,  180.,  360.])

References

Links Site
math module Python doc
Python: converting radians to degrees stackoverflow
numpy.radians() and deg2rad() in Python geeksforgeeks.org
numpy.radians docs.scipy.org
numpy.deg2rad docs.scipy.org
numpy.degrees docs.scipy.org


Card image cap
profile-image
Daidalos

Je développe le présent site avec le framework python Django. Je m'intéresse aussi actuellement dans le cadre de mon travail au machine learning pour plusieurs projets (voir par exemple) et toutes suggestions ou commentaires sont les bienvenus !