Python math degrees to radians

How to Convert Degrees to Radians in Python?

In this Python tutorial, I will explain to you, how to convert degrees to radians in Python.

  • Degrees: A full circle is divided into 360 equal parts, each part is known as a degree.
  • Radians: In radians, a full circle is equal to 2π, where π (pi) is approximately equal to 3.14159265358979323846.

The relationship between degrees and radians is given by the formula:

Python degrees to radians

Python has a built-in module that can be used for the mathematical task on numbers. The math module contains functions for calculating the various trigonometric ratios for a given angle.

The math module presents two angles conversion function which is degrees() and radians(). The math module has a set of methods.

In Python, math.radians() method is used to convert a degree value to radians. So, we will first import math module.

import math print(math.radians(120))

Once you execute the code, “math.radians(120)”, will print like 2.0943951023931953.

You can refer to the below screenshot:

Читайте также:  Php call to undefined function split

Python degrees to radians

This is how to convert degrees to radians in Python.

Convert Degrees to Radians in Python

Here is a different way to convert degrees to radians in Python.

  • The first step is to import the necessary libraries. Python’s math library contains a constant for π (pi) which we will be using.
  • Next, let’s create a function that takes an angle in degrees as an argument and returns its equivalent in radians.
def degrees_to_radians(degrees): return degrees * (math.pi / 180)
  • In a practical program, you might want to allow the user to input the angle in degrees. You can do this using the input() function.
degrees = float(input("Enter angle in degrees: ")) radians = degrees_to_radians(degrees) print(f" degrees is equal to radians")
  • Python’s math library also includes a built-in function to convert degrees to radians, which is math.radians(). This can be used as an alternative to the function we created earlier.
radians = math.radians(degrees) print(f" degrees is equal to radians")

Below is the complete code:

import math def degrees_to_radians(degrees): return degrees * (math.pi / 180) # Using custom function degrees = float(input("Enter angle in degrees: ")) radians = degrees_to_radians(degrees) print(f" degrees is equal to radians using the custom function") # Using built-in function radians = math.radians(degrees) print(f" degrees is equal to radians using the built-in function")

You can check out the output like below:

How to convert degrees to radians in Python

Convert degrees to radians using NumPy in Python

Let’s see how to convert degrees to radians using NumPy in Python.

To convert degrees to radians in Python, we have to import numpy package first. It has an inbuilt function name deg2rad() which can directly convert degrees to radians.

import numpy as np print("degrees to radian: ",np.deg2rad(2))

After writing the above code, Ones you will print “np.deg2rad(2)” then the output will appear as “degrees to radian: 0.03490658503988659“. Here, np.deg2rad(2) will convert degrees to radians.

You can refer to the below screenshot:

python deg to rad

Conclusion

We can easily use the Python Math module to convert degrees to radians in Python. I have explained examples of Python degrees to radians.

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Перевод градусов в радианы и наоборот в 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 can I convert radians to degrees with Python?

In the math module, I could only find math.cos(x) , with cos/sin/tan/acos/asin/atan. This returns the answer in radians. How can I get the answer in degrees? Here’s my code:

import math x = math.cos(1) y = x * 180 / math.pi print(y) 30.9570417874 

@lucase.62, Mark is correct. The cos function operates on an angle as the input, 1 in your example. On your calculator, this angle is in degress, in Python, this angle must be given in radians. The return value, x in your example, is a dimensionless number. On your calculator you have calculated the cos of 1 degree. In your Python example, you have calculated the cos of 1 radian, which is equivalent to 57.296 degrees.

cos takes an angle as input and produces a ratio as output. Trying to convert the output to degrees as you’ve done in your example doesn’t make sense at all. You need to convert the input 1 from degrees to radians instead. If you were using acos it would be the other way around, the input is a ratio and the output is radians.

7 Answers 7

Python includes two functions in the math package; radians converts degrees to radians, and degrees converts radians to degrees.

To match the output of your calculator you need:

>>> math.cos(math.radians(1)) 0.9998476951563913 

Note that all of the trig functions convert between an angle and the ratio of two sides of a triangle. cos, sin, and tan take an angle in radians as input and return the ratio; acos, asin, and atan take a ratio as input and return an angle in radians. You only convert the angles, never the ratios.

This is a fantastic response. Your example is clear but your «bonus» explanation is really helpful. I was curious about this exact thing.

If anyone wonders, numpy also have those functions, to convert entire arrays in one go. It also has them under the more explicit names rad2deg and deg2rad .

Python convert radians to degrees or degrees to radians:

What are Radians and what problem does it solve?:

Radians and degrees are two separate units of measure that help people express and communicate precise changes in direction. Wikipedia has some great intuition with their infographics on how one Radian is defined relative to degrees:

Conversion from radians to degrees

Python examples using libraries calculating degrees from radians:

>>> import math >>> math.degrees(0) #0 radians == 0 degrees 0.0 >>> math.degrees(math.pi/2) #pi/2 radians is 90 degrees 90.0 >>> math.degrees(math.pi) #pi radians is 180 degrees 180.0 >>> math.degrees(math.pi+(math.pi/2)) #pi+pi/2 radians is 270 degrees 270.0 >>> math.degrees(math.pi+math.pi) #2*pi radians is 360 degrees 360.0 

Python examples using libraries calculating radians from degrees:

>>> import math >>> math.radians(0) #0 degrees == 0 radians 0.0 >>> math.radians(90) #90 degrees is pi/2 radians 1.5707963267948966 >>> math.radians(180) #180 degrees is pi radians 3.141592653589793 >>> math.radians(270) #270 degrees is pi+(pi/2) radians 4.71238898038469 >>> math.radians(360) #360 degrees is 2*pi radians 6.283185307179586 

The mathematical notation:

Mathematical notation of degrees and radians

You can do degree/radian conversion without python libraries:

If you roll your own degree/radian converter, you have to write your own code to handle edge cases.

Mistakes here are easy to make, and will hurt just like it hurt the developers of the 1999 mars orbiter, who sunk $125m dollars crashing it into Mars because of non intuitive edge case here.

>>> 0 * 180.0 / math.pi #0 radians is 0 degrees 0.0 >>> (math.pi/2) * 180.0 / math.pi #pi/2 radians is 90 degrees 90.0 >>> (math.pi) * 180.0 / math.pi #pi radians is 180 degrees 180.0 >>> (math.pi+(math.pi/2)) * 180.0 / math.pi #pi+(pi/2) radians is 270 degrees 270.0 >>> (2 * math.pi) * 180.0 / math.pi #2*pi radians is 360 degrees 360.0 

Degrees to radians:

>>> 0 * math.pi / 180.0 #0 degrees in radians 0.0 >>> 90 * math.pi / 180.0 #90 degrees in radians 1.5707963267948966 >>> 180 * math.pi / 180.0 #180 degrees in radians 3.141592653589793 >>> 270 * math.pi / 180.0 #270 degrees in radians 4.71238898038469 >>> 360 * math.pi / 180.0 #360 degrees in radians 6.283185307179586 

Expressing multiple rotations with degrees and radians

Single rotation valid radian values are between 0 and 2*pi. Single rotation degree values are between 0 and 360. However if you want to express multiple rotations, valid radian and degree values are between 0 and infinity.

>>> import math >>> math.radians(360) #one complete rotation 6.283185307179586 >>> math.radians(360+360) #two rotations 12.566370614359172 >>> math.degrees(12.566370614359172) #math.degrees and math.radians preserve the 720.0 #number of rotations 

Collapsing multiple rotations:

You can collapse multiple degree/radian rotations into a single rotation by modding against the value of one rotation. For degrees you mod by 360, for radians you modulus by 2*pi.

>>> import math >>> math.radians(720+90) #2 whole rotations plus 90 is 14.14 radians 14.137166941154069 >>> math.radians((720+90)%360) #14.1 radians brings you to 1.5707963267948966 #the end point as 1.57 radians. >>> math.degrees((2*math.pi)+(math.pi/2)) #one rotation plus a quarter 450.0 #rotation is 450 degrees. >>> math.degrees(((2*math.pi)+(math.pi/2))%(2*math.pi)) #one rotation plus a quarter 90.0 #rotation brings you to 90. 

Fundamental education on Radians and Degrees

Источник

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