Skip to content

Commit

Permalink
Modify quadratic slightly, add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ekiefl committed Jan 18, 2025
1 parent 310a9c5 commit c8146b8
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
14 changes: 12 additions & 2 deletions pooltool/ptmath/roots/quadratic.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from typing import Tuple

import numpy as np
from numba import jit

import pooltool.constants as const
Expand All @@ -9,10 +10,19 @@
def solve(a: float, b: float, c: float) -> Tuple[float, float]:
"""Solve a quadratic equation At^2 + Bt + C = 0 (just-in-time compiled)"""
if a == 0:
u = -c / b
return u, u
if b == 0:
# c=0 => infinite solutions, c≠0 => no solutions
return np.nan, np.nan
else:
# Linear: b * t + c = 0 => t = -c/b
return -c / b, np.nan

bp = b / 2
delta = bp * bp - a * c

if delta < 0:
return np.nan, np.nan

u1 = (-bp - delta**0.5) / a
u2 = -u1 - b / a
return u1, u2
24 changes: 24 additions & 0 deletions tests/ptmath/roots/test_quadratic.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,27 @@ def test_solve_large_values():
# required relative tolerance required to pass this test is pretty large (1e-2).
assert pytest.approx(solutions[0], rel=1e-2) == 1e-7
assert pytest.approx(solutions[1], rel=1e-2) == 1e7


def test_solve_linear_equation():
# a=0, b≠0 => linear equation b*t + c = 0 => t=-c/b
# e.g. 2t + 4 = 0 => t=-2
r1, r2 = solve(0.0, 2.0, 4.0)
assert r1 == -2.0
assert math.isnan(r2) # The second "root" should be NaN for a linear equation


def test_solve_degenerate_no_solution():
# a=0, b=0, c≠0 => no solutions
# e.g. 0*t^2 + 0*t + 5 = 0 => no real solution
r1, r2 = solve(0.0, 0.0, 5.0)
assert math.isnan(r1)
assert math.isnan(r2)


def test_solve_degenerate_infinite_solutions():
# a=0, b=0, c=0 => infinite solutions
# e.g. 0*t^2 + 0*t + 0 = 0 => t can be anything
r1, r2 = solve(0.0, 0.0, 0.0)
assert math.isnan(r1)
assert math.isnan(r2)

0 comments on commit c8146b8

Please sign in to comment.