-
Notifications
You must be signed in to change notification settings - Fork 18
pymath.solve_quadratic
Daniel Flassig edited this page Jul 27, 2026
·
1 revision
Solves the quadratic equation a x² + b x + c == 0, returning its two real roots ordered by absolute value, or nil where no finite real root exists.
r_small, r_large = pymath.solve_quadratic(a, b, c [, tolerance])| Parameter | Type | Description |
|---|---|---|
a |
number |
Coefficient of x². |
b |
number |
Coefficient of x. |
c |
number |
The constant term. |
tolerance |
number (optional)
|
Non-negative bound on the imaginary part below which a complex pair still counts as a (double) real root. Default: an implementation defined tolerance. |
| Type | Description |
|---|---|
r_small |
The root of smaller absolute value, or nil if the equation has no real root at all. |
r_large |
The root of larger absolute value, or nil if there is no second finite root. |
- The two roots are labelled by their absolute value, not by their value: for
x² + 3x + 2the result is-1, -2. Usepymath.solve_polynomialif you need them in ascending order. - The ordering is what makes the degenerate cases predictable: when the equation collapses to a linear one (
aat or below the internal tolerance), the surviving root is always returned asr_smallandr_largeisnil. So a single non-nilfirst return value is all you need to check. - A double root is returned twice, so
r_small == r_large. - A complex pair that lies closer to the real axis than
toleranceis snapped to a double root. Raisetoleranceto accept grazing intersections, lower it to reject them. - Both return values are
nilfor a genuinely complex pair, and also for the identically zero equation (0, 0, 0), where every number is a root. - The function is implemented with careful analysis of floating point accuracy
local r1, r2 = pymath.solve_quadratic(1, -3, 2) -- x² - 3x + 2
-- r1 == 1.0, r2 == 2.0
local s1, s2 = pymath.solve_quadratic(1, 3, 2) -- x² + 3x + 2
-- s1 == -1.0, s2 == -2.0 -- ordered by absolute value!
local d1, d2 = pymath.solve_quadratic(1, -2, 1) -- x² - 2x + 1
-- d1 == 1.0, d2 == 1.0 -- double root, returned twice
local l1, l2 = pymath.solve_quadratic(0, 2, -4) -- degenerates to 2x - 4
-- l1 == 2.0, l2 == nil
local c1, c2 = pymath.solve_quadratic(1, 0, 1) -- x² + 1
-- c1 == nil, c2 == nil -- no real rootMinimum PYTHA Version: V27