Skip to content

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 .
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.

Return value

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.

Notes:

  • The two roots are labelled by their absolute value, not by their value: for x² + 3x + 2 the result is -1, -2. Use pymath.solve_polynomial if you need them in ascending order.
  • The ordering is what makes the degenerate cases predictable: when the equation collapses to a linear one (a at or below the internal tolerance), the surviving root is always returned as r_small and r_large is nil. So a single non-nil first 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 tolerance is snapped to a double root. Raise tolerance to accept grazing intersections, lower it to reject them.
  • Both return values are nil for 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

Example:

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 root

Version Support:

Minimum PYTHA Version: V27

See also:

pymath, pymath.solve_polynomial, pymath.solve_linear

Clone this wiki locally