Python rad to degree

How to convert radians to degrees (or the opposite) in python ?

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.

Читайте также:  File extensions php ini

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 
>>> 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

  • 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

Benjamin

Greetings, I am Ben! I completed my PhD in Atmospheric Science from the University of Lille, France. Subsequently, for 12 years I was employed at NASA as a Research Scientist focusing on Earth remote sensing. Presently, I work with NOAA concentrating on satellite-based Active Fire detection. Python, Machine Learning and Open Science are special areas of interest to me.

Skills

Источник

4 Unique Ways To Convert Radians to Degrees in Python

radians to degrees python

Mathematically we are all familiar with radians and degrees. Radians are something that intercepts an arc on the circle equal in length. A degree is a unit of the angle of measurement. And we also know that how to convert the radians to degrees. Now let us think about how to implement it in python. There are four unique ways available to convert radians to degrees in python. In this article, we will learn all the four possible ways.

A complete revolution of a circle in anticlockwise is represented by 2π in radians, and we can describe it in degree as 360 o . Based on this statement, we can define the equation as 2π=360 o . And also π=180 o . So from this, we can easily say that π radian is equal to 180 degrees.

Methods to convert radians to degrees:

Method 1: Using the formula to convert radians to degrees in python

There is a standard method available to convert radians to degrees using a formula. We can implement this method by function. The conversion formula is:

Code to convert radians to degrees in python

import math def degree_converter(x): pi_value=math.pi degree=(x*180)/pi_value return degree print("The degree of the given radian is :",degree_converter(1.5708))

Import math. Create a function named degree, including a pi value. I am using the above-given formula to calculate the degree of the given radian. Return the value of the degree.

The degree of the given radian is : 90.0002104591497

Method 2: Using degrees() function to convert radians to degrees in python

degrees() is a built-in function that is already available in python. This will convert the given radians into degrees.

Syntax

Parameter

Radian value: input radian values

Returns

Degree of the given radian value

Code to convert radians to degrees in python

import math radians = 1.5708 degrees = math.degrees(radians) print("The degree of the given radian is :",degrees)

Import a math function. Use the built-in function to get the degrees of the given radian. Print the degrees.

The degree of the given radian is: 90.00021045914971

Method 3:Using numpy.degrees() to convert radians to degrees in python

We can also use the numpy module to convert the radians to degrees. numpy.degrees() is a function that is useful to get the degrees of the given radians. This is one of the built-in functions in the numpy module.

Syntax

numpy.degrees(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) =

Parameters

  • x: Input radian
  • out: A memory to store the result
  • where: array-like
  • **kwargs: For other keyword-only arguments, see the ufunc docs.

Returns

Degree value of the given radian

Code

import numpy radian = 1.5708 degrees=numpy.degrees(radian) print("The degree of the given radian is:",degrees)

Import a numpy module. Declare a variable radian. Assign a value for the radian variable. Use the numpy.degrees() function. Print the value of the degrees.

The degree of the given radian is: 90.00021045914971

Method 4: Using np.deg2rad to convert radians to degrees in python

In numpy, there is another function available to convert the radian to degrees. That is np.rad2deg function. This is a function available in the numpy module.

Syntax

numpy.rad2deg(x, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj]) =

Parameters

  • x: Input radian
  • out: A memory to store the result
  • where: array-like
  • **kwargs: For other keyword-only arguments, see the ufunc docs.

Returns

Degrees of the given radian

Code

import numpy as np radian = 1.5708 degrees=np.rad2deg(radian) print("The degree of the given radian is :",degrees)

Import a numpy module as np. Give an input radian. Use the np.rad2deg function. Print the degree.

The degree of the given radian is : 90.00021045914971

Bonus section: How to convert degrees to radians

So far, we have entirely learned how to convert the radian values to degrees. As additional knowledge, we will learn the reverse process, that is, degrees to radians. We will now know how to get the radians for the values of the given degree. We will use math.radians() function to get the radians of the given values.

Code

import math degrees = 90 radians = math.radians(degrees) print("The radian value is:",radians)

Import a necessary module. Here we need to import a math module. Give the input degrees. Use the radians() function to get the radians. This function will return the radian value for the given degree. Print the result.

The radian value is: 1.5707963267948966

There are four possible ways to convert the radians to degrees in python namely, math.degrees(), numpy.degree(), numpy.rad2degree() and custom function.

We can convert the radians to degrees by a normal method using the formula, degrees() function, numpy.degrees(), and np.rad2deg() function.

Conclusion

In this article, we have learned how to get the degree value by using radian values in python. Learn all the four methods to get the degree values. While learning something, try to know all the possible ways. That is the way to become a good programmer. Try to solve the programs on your own.

In case of any queries, let us know in the comment section. We will help you. Learn python with us. Shine in your way. Happy coding.

Источник

Перевод градусов в радианы и наоборот в Python

degrees() и radians () в Python — это методы, указанные в математическом модуле в Python 3 и Python 2. Часто требуется выполнить математические вычисления перевода радианов в градусы в Python и наоборот, особенно в области геометрии.

Что такое функция radians() в Python?

Python radians() — это встроенный метод, определенный в математическом модуле, который используется для преобразования угла x (который является параметром) из градусов в радианы. Например, если x передается в качестве параметра в градусах, то функция(радианы(x)) возвращает значение этого угла в радианах.

Мы будем использовать математический модуль, импортировав его. После импорта модуля мы можем вызвать функцию radians(), используя статический объект.

Функция Python radians()

Синтаксис

Здесь var — это переменная, которую мы должны преобразовать из градусов в радианы.

Параметры

Метод принимает один аргумент var, который принимает значения числового типа данных и выдает TypeError, если передается параметр любого другого типа данных.

Возвращаемое значение

radians() возвращает значение числа в радианах в типе данных float.

Примеры программ с использованием метода radians() в Python

Пример 1

Напишите программу, демонстрирующую работу метода radians() в Python.

В приведенном выше примере мы видели, что, минуя допустимый параметр в функции градусов, мы получаем значение угла в радианах. Здесь мы прошли разные углы и получили разные значения.

Пример 2

Напишите программу для передачи значения вне допустимого диапазона из функции radians() и отображения вывода.

В этом примере мы видели, что передача параметра, который не является реальным числом, вызывает ошибку TypeError.

Python radians() со списком и кортежем

В первых трех операторах мы использовали функцию radians () с нулями, положительными целыми и отрицательными целыми значениями в качестве аргументов. В следующих двух утверждениях мы использовали функцию с положительными и отрицательными десятичными значениями в качестве параметров.

В следующих двух утверждениях мы использовали метод radians () для элементов Python Tuple и Python List. Если вы наблюдаете приведенный выше вывод, функция radians() работает с ними правильно.

Мы попробовали метод radians() непосредственно для нескольких значений. Затем мы использовали функцию radians() для значений круговой диаграммы.

В последнем коде мы использовали функцию radians() для значения String. Как мы уже говорили, оно возвращает TypeError в качестве вывода.

Функция degrees() в Python

Python Degrees() — это встроенный метод, определенный в математическом модуле, который используется для преобразования угла x (который является параметром) из радианов в градусы. Например, если x передается в качестве параметра в функцию градусов (degrees(x)), она возвращает значение угла в градусах. Функция Python math.degrees() существует в стандартной математической библиотеке.

Источник

How to convert radian to degree in Python

We all have dealt with radians and degrees in our school and college days. Yes, in Mathematics and Physics.
Radians and Degree are used to represent angles. For eg, 1.4 radians or 30 degrees.
In this tutorial, we will learn how to convert radian to degree in Python.

Radian to Degree in Python

There are two methods for the conversion.

Let’s start with the first one.

Using formula(The obvious method)

We all know the formula for converting radian into degree,
degree=(radian*180)/pi

Let’s write the code in Python.

import math def degree(x): pi=math.pi degree=(x*180)/pi return degree

This is a simple code written in Python in which we define a function degree(x) which takes radian value as a parameter and returns the corresponding value in degree.
Here, We import math library which provides different mathematical functions, pi in this case.
math.pi returns the value of pi which is stored in a variable x.

Finally, Let’s call the function.

print("Value in Degree:",degree(1.5))
Value in Degree: 85.94366926962348

degrees() method

math library includes a method degrees() which takes radian value as parameter and returns value in Degree.

Again, we define a function degree(x) which takes radian value as a parameter and returns the corresponding value in degree.

import math def degree(x): x=math.degrees(x) return x

Now calling the function in the same way as in the previous method.

print("Value in Degree:",degree(1.5))
Value in Degree: 85.94366926962348

We hope you got a clear idea on How to convert radian to degree in Python.

In addition, radians() is a method that takes degree value as parameter and returns value in radians.

Источник

Оцените статью