TExcelTAD
Home › Pre-Calculus, Geometry & Trigonometry › Geometry and Trig with Python

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 2π2\pi radians, so 180∘=π180^\circ = \pi radians. Forgetting this is the most common trig bug in code:

python · try it yourself
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

sin⁡30∘\sin 30^\circ is exactly 12\frac{1}{2} in mathematics, but the computer shows 0.49999999999999994 because π\pi (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) x2+y2\sqrt{x^2 + y^2}, 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 (x,y)(x, y) from the +x axis, in (−π,π](-\pi, \pi] atan2(1, -1) → 3π/43\pi/4

Why atan2 and not atan

math.atan(y / x) only knows the ratio y/xy / x, so it cannot tell (1,1)(1, 1) from (−1,−1)(-1, -1), and it crashes when x=0x = 0. atan2(y, x) looks at the signs of both coordinates and returns the correct angle in every quadrant:

python · try it yourself
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 2\sqrt{2} and 25π25\pi, which is handy for checking homework-style answers:

python · try it yourself
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 (2,3/2)(2, 3/2) is the midpoint of the hypotenuse BC‾\overline{BC} and its radius 5/25/2 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 25π25\pi and 2\sqrt{2}.

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:

python · try it yourself
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 θ\theta on a circle of radius rr around (cx,cy)(c_x, c_y) is (cx+rcos⁡θ,cy+rsin⁡θ)(c_x + r\cos\theta, c_y + r\sin\theta).

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 π\pi, then check with math.radians.

Answer

π/4≈0.7854\pi/4 \approx 0.7854, 2π/3≈2.09442\pi/3 \approx 2.0944, 3π/2≈4.71243\pi/2 \approx 4.7124

Solution
radians=degrees×π/18045∘→45π/180=π/4120∘→120π/180=2π/3270∘→270π/180=3π/2\begin{aligned} \text{radians} &= \text{degrees} \times \pi / 180 \\ 45^\circ &\to 45\pi/180 = \pi/4 \\ 120^\circ &\to 120\pi/180 = 2\pi/3 \\ 270^\circ &\to 270\pi/180 = 3\pi/2 \end{aligned}
python · try it yourself
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 (−3,−3)(-3, -3) is in the third quadrant, on the diagonal, so its angle is 225°. atan2 reports angles in (−180∘,180∘](-180^\circ, 180^\circ], and 225∘−360∘=−135∘225^\circ - 360^\circ = -135^\circ.

Exercise 3: Exact triangle

Use SymPy to find the exact perimeter and area of the triangle with corners (0,0)(0, 0), (2,0)(2, 0), (1,3)(1, 3).

Answer

Perimeter 2+2102 + 2\sqrt{10}, area 33.

Solution

The two slanted sides each have length 12+32=10\sqrt{1^2 + 3^2} = \sqrt{10}, and the base is 2. The area is 12×base×height=12×2×3=3\frac{1}{2} \times \text{base} \times \text{height} = \frac{1}{2} \times 2 \times 3 = 3.

python · try it yourself
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 (1,1)(1, 1), starting at angle 0°. Round to 3 decimals.

Answer

(3,1)(3, 1), (1,3)(1, 3), (−1,1)(-1, 1), (1,−1)(1, -1)

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.

python · try it yourself
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?

  1. The sine of 90°, which is 1
  2. The sine of 90 radians
  3. An error, because 90 is too large
  4. The sine of 90 gradians

Why prefer math.atan2(y, x) over math.atan(y / x)?

  1. It is faster
  2. It returns degrees
  3. It uses the signs of xx and yy to give the right quadrant and handles x=0x = 0
  4. It works only for positive numbers

Why call plt.axis("equal") when drawing shapes?

  1. So one unit has the same length on both axes and circles look round
  2. To hide the axes
  3. To fill the shapes
  4. To set the figure size