Fixed ellipse after writing some tests to identify the problem

This commit is contained in:
Chris Proctor 2025-06-26 12:27:07 -04:00
parent edac317460
commit c027ffbf9f
3 changed files with 36 additions and 8 deletions

View File

@ -17,6 +17,7 @@ def ellipse(rx, ry, num_points, points_to_draw=None):
for i in range(points_to_draw or num_points): for i in range(points_to_draw or num_points):
φi = get_angle(rx, ry, num_points, i) φi = get_angle(rx, ry, num_points, i)
di = get_distance(rx, ry, num_points, i) di = get_distance(rx, ry, num_points, i)
print(i, φi, di)
left(φi) left(φi)
forward(di) forward(di)
left(-π/2) left(-π/2)
@ -79,9 +80,10 @@ def project_onto_basis(vec, basis):
is perpendicular (vec_b). is perpendicular (vec_b).
""" """
v0, v1 = vec v0, v1 = vec
b0, b1 = basis unit_basis = normalize(basis)
len_a = dot(vec, basis) b0, b1 = unit_basis
vec_a = (len_a * v0, len_a * v1) len_a = dot(vec, unit_basis)
vec_a = (len_a * b0, len_a * b1)
vec_b = get_vector(vec_a, vec) vec_b = get_vector(vec_a, vec)
return vec_a, vec_b return vec_a, vec_b
@ -93,6 +95,13 @@ def dot(vec0, vec1):
x1, y1 = vec1 x1, y1 = vec1
return x0 * x1 + y0 * y1 return x0 * x1 + y0 * y1
def normalize(vec):
"""Scales vec to magnitude 1.
"""
x, y = vec
len_vec = mag(vec)
return x / len_vec, y / len_vec
def mag(vec): def mag(vec):
"""Returns the magnitude, or length, of a vector. """Returns the magnitude, or length, of a vector.
We can simplify the familiar formula sqrt(x*x + y*y) We can simplify the familiar formula sqrt(x*x + y*y)

View File

@ -1,5 +0,0 @@
from ellipse import ellipse
ellipse(100, 200, 1024)
input()

View File

@ -0,0 +1,24 @@
# To run these tests run: python -m unittest tests
from unittest import TestCase
from ellipse import *
from math import sqrt
class TestEllipseFunctions(TestCase):
def test_normalize(self):
observed = normalize((0, 1))
expected = (0, 1)
self.assertEqual(observed, expected)
observed = normalize((2, 0))
expected = (1, 0)
self.assertEqual(observed, expected)
observed = normalize((1, 1))
expected = (1/sqrt(2), 1/sqrt(2))
self.assertEqual(observed, expected)
def test_project_onto_basis(self):
observed = project_onto_basis((4, 3), (4, 0))
expected = ((4, 0), (0, 3))
self.assertEqual(observed, expected)