How to Convert Radians to Degrees in Python
Angles in Python’s math functions are often expressed in radians, but most people are familiar with degrees. Whether you’re doing trigonometry, working with graphics, or just need a quick conversion, Python makes converting radians to degrees straightforward. Here are the best ways, with code examples and explanations.
Table of Content
Why Convert Radians to Degrees?
- Trigonometry: Most angles in school and engineering are in degrees, but Python’s math functions use radians.
- Graphics/Plotting: Rotate shapes or set angles more intuitively in degrees.
- User Input/Output: Make results friendlier for most users and interfaces.
01. Using math.degrees()
(Recommended)
The math.degrees()
function quickly converts radians to degrees with correct rounding and avoids manual calculation.
import math
angle_rad = math.pi / 2
angle_deg = math.degrees(angle_rad)
print(angle_deg)
Output:
90.0
math.degrees()
is available in Python’s standard math module.- Takes a number in radians and returns the angle in degrees as a float.
02. Using the Radians-to-Degrees Formula
The mathematical formula to convert radians to degrees is:degrees = radians × (180 / Ï€)
import math
angle_rad = 1.5
angle_deg = angle_rad * 180 / math.pi
print(angle_deg)
Output:
85.94366926962348
- Always import
math.pi
for the most accurate value of π. - The result is a float, as most angles are not whole numbers.
03. Converting a List or Array of Radians
Use a list comprehension or NumPy for bulk conversion.
import math
angles_rad = [0, math.pi/6, math.pi/4, math.pi/2]
angles_deg = [math.degrees(r) for r in angles_rad]
print(angles_deg)
Output:
[0.0, 30.0, 45.0, 90.0]
With NumPy:
import numpy as np
arr_rad = np.array([0, np.pi/2, np.pi, 2*np.pi])
arr_deg = np.degrees(arr_rad)
print(arr_deg)
Output:
[ 0. 90. 180. 360.]
04. Comparison Table: Conversion Methods
Method | Single Value | Multiple Values | Best For |
---|---|---|---|
math.degrees() | Yes | With list comp | Standard, most use cases |
radians × 180 / math.pi | Yes | With list comp | Quick math, full control |
numpy.degrees() | Yes | Yes (arrays) | Batch processing, scientific |
Conclusion
Converting radians to degrees in Python is both quick and accurate. Use math.degrees()
for any single value, the formula for custom calculations, or numpy.degrees()
if you’re working with arrays. This ensures your code is readable and your results match common expectations in engineering, math, or user-facing apps.
Comments
Post a Comment