Geometry and Trig with Python
Python is a calculator, a proof checker and a drawing board for this course. This lesson shows the three tools used throughout: the math module for numbers and trigonometry, SymPy's geometry objects for exact answers, and Matplotlib for drawing shapes.
The math module: trig works in radians
Python's math.sin, math.cos and math.tan expect angles in radians, not degrees. A full turn is 360° or radians, so radians. Forgetting this is the most common trig bug in code:
import math
print("sin(30) =", math.sin(30)) # 30 RADIANS, not degrees
print("sin(30°) =", math.sin(math.radians(30))) # what you probably meant
print("radians(180) =", math.radians(180))
print("degrees(pi / 2) =", math.degrees(math.pi / 2))
print("round(sin 30°, 12) =", round(math.sin(math.radians(30)), 12))sin(30) = -0.9880316240928618
sin(30°) = 0.49999999999999994
radians(180) = 3.141592653589793
degrees(pi / 2) = 90.0
round(sin 30°, 12) = 0.5
is exactly in mathematics, but the computer shows 0.49999999999999994 because (and so the radian value) cannot be stored exactly in floating point. Rounding the result is the usual fix when you print. Radians are explained fully in Angles and Radians.
| Function | What it does | Example |
|---|---|---|
math.radians(d) |
degrees → radians | radians(90) → 1.5707… |
math.degrees(r) |
radians → degrees | degrees(math.pi) → 180.0 |
math.hypot(x, y) |
, the length of a vector or hypotenuse | hypot(3, 4) → 5.0 |
math.dist(p, q) |
distance between two points | dist((0, 0), (6, 8)) → 10.0 |
math.atan2(y, x) |
the angle of the point from the +x axis, in | atan2(1, -1) → |
Why atan2 and not atan
math.atan(y / x) only knows the ratio , so it cannot tell from , and it crashes when . atan2(y, x) looks at the signs of both coordinates and returns the correct angle in every quadrant:
import math
points = [(1, 1), (-1, 1), (-1, -1), (1, -1), (0, 2)]
for x, y in points:
a2 = math.degrees(math.atan2(y, x))
a1 = math.degrees(math.atan(y / x)) if x != 0 else None
print(f"({x:2}, {y:2}) atan2 → {a2:7.1f}° atan(y/x) → {a1}")
print("hypot(5, 12) =", math.hypot(5, 12))( 1, 1) atan2 → 45.0° atan(y/x) → 45.0
(-1, 1) atan2 → 135.0° atan(y/x) → -45.0
(-1, -1) atan2 → -135.0° atan(y/x) → 45.0
( 1, -1) atan2 → -45.0° atan(y/x) → -45.0
( 0, 2) atan2 → 90.0° atan(y/x) → None
hypot(5, 12) = 13.0
Tip: In games, "which way should this turret face?" is almost always
atan2(target_y − y, target_x − x). See atan2 in Game Math.
SymPy geometry: exact answers
Floating point gives approximations. SymPy's Point, Triangle and Circle keep exact values such as and , which is handy for checking homework-style answers:
from sympy import Point, Triangle, Circle
A, B, C = Point(0, 0), Point(4, 0), Point(0, 3)
t = Triangle(A, B, C)
print("area:", t.area, " perimeter:", t.perimeter)
print("right triangle?", t.is_right())
print("circumcircle:", t.circumcircle)
c1 = Circle(Point(0, 0), 5)
c2 = Circle(Point(6, 0), 5)
print("area of c1:", c1.area, " circumference:", c1.circumference)
print("c1 ∩ c2:", c1.intersection(c2))
print("distance A to (1, 1):", A.distance(Point(1, 1)))area: 6 perimeter: 12
right triangle? True
circumcircle: Circle(Point2D(2, 3/2), 5/2)
area of c1: 25*pi circumference: 10*pi
c1 ∩ c2: [Point2D(3, -4), Point2D(3, 4)]
distance A to (1, 1): sqrt(2)
Notice the circumcircle of the right triangle: its centre is the midpoint of the hypotenuse and its radius is half the hypotenuse. That is Thales' theorem, proved in Geometric Proofs. SymPy prints 25*pi and sqrt(2) in Python syntax; read them as and .
Matplotlib: drawing shapes
A picture catches mistakes that numbers hide. plt.fill draws a filled polygon from lists of x and y values, plt.Circle adds a circle, and plt.axis("equal") makes one unit the same length on both axes so circles look round:
import numpy as np
import matplotlib.pyplot as plt
xs = [0, 4, 0]
ys = [0, 0, 3]
theta = np.linspace(0, 2 * np.pi, 7)[:-1] # 6 corners of a hexagon
hx = 7 + 1.5 * np.cos(theta)
hy = 1.5 + 1.5 * np.sin(theta)
plt.figure(figsize=(6, 4))
plt.fill(xs, ys, alpha=0.4, label="right triangle")
plt.fill(hx, hy, alpha=0.4, label="regular hexagon")
plt.gca().add_patch(plt.Circle((2, 1.5), 2.5, fill=False, color="tab:red", label="circumcircle"))
plt.axis("equal")
plt.grid(True, alpha=0.3)
plt.legend(loc="upper right")
plt.title("Shapes drawn from coordinates")
print("hexagon corners:", len(hx))hexagon corners: 6
plt.fill closes the outline for you, so you list each corner once. The hexagon's corners come from cos and sin: a point at angle on a circle of radius around is .
In software
These few functions cover a surprising amount of real code: hypot and dist for ranges and collision radii, atan2 for aiming and steering, radians for every graphics and physics API, and exact symbolic geometry in CAD tools and test suites. The same ideas in NumPy work on thousands of points at once (see NumPy).
Exercises
Exercise 1: Degrees to radians
Convert 45°, 120° and 270° to radians as multiples of , then check with math.radians.
Answer
, ,
Solution
import math
for d in [45, 120, 270]:
print(d, round(math.radians(d), 4))45 0.7854
120 2.0944
270 4.7124
Exercise 2: A quadrant check
What does math.degrees(math.atan2(-3, -3)) print? Decide the quadrant first.
Answer
-135.0
Solution
The point is in the third quadrant, on the diagonal, so its angle is 225°. atan2 reports angles in , and .
Exercise 3: Exact triangle
Use SymPy to find the exact perimeter and area of the triangle with corners , , .
Answer
Perimeter , area .
Solution
The two slanted sides each have length , and the base is 2. The area is .
from sympy import Point, Triangle
t = Triangle(Point(0, 0), Point(2, 0), Point(1, 3))
print(t.perimeter, t.area)2 + 2*sqrt(10) 3
Exercise 4: Points on a circle
Write a loop that prints the 4 corners of a square inscribed in the circle of radius 2 centred at , starting at angle 0°. Round to 3 decimals.
Answer
, , ,
Solution
The corners sit at 0°, 90°, 180° and 270°. Rounding hides tiny floating-point leftovers such as 1.2e-16; adding 0.0 turns a -0.0 into 0.0.
import math
for k in range(4):
a = math.radians(90 * k)
print((round(1 + 2 * math.cos(a), 3) + 0.0, round(1 + 2 * math.sin(a), 3) + 0.0))(3.0, 1.0)
(1.0, 3.0)
(-1.0, 1.0)
(1.0, -1.0)
Test yourself
What does math.sin(90) compute in Python?
- The sine of 90°, which is 1
- The sine of 90 radians
- An error, because 90 is too large
- The sine of 90 gradians
Why prefer math.atan2(y, x) over math.atan(y / x)?
- It is faster
- It returns degrees
- It uses the signs of and to give the right quadrant and handles
- It works only for positive numbers
Why call plt.axis("equal") when drawing shapes?
- So one unit has the same length on both axes and circles look round
- To hide the axes
- To fill the shapes
- To set the figure size