Complex numbers
Most polynomials have roots off the real line. x³ − 2 has one real root, ∛2, and two more at ∛2·(−1/2 ± i√3/2). These are algebraic numbers too, and the library holds them as exactly as the real ones.
A box that holds exactly one root
A non-real root is stored as its polynomial plus a rectangle in the complex plane. Floating point finds approximate roots first (Durand–Kerner); each is then proven with the Krawczyk test. Writing z = x + iy turns p(z) = 0 into two real equations in x and y. For a box X with midpoint m and an approximate inverse Y of the Jacobian,
is computed in exact interval arithmetic. If K(X) lands strictly inside X, the box holds exactly one root, and K(X) ∩ X is a smaller box that still holds it. Boxes for different roots are checked to be disjoint, so every root is counted once. Repeating the step shrinks the box as far as you like.
Arithmetic and display
Sums and products work exactly as for real numbers: a resultant, factored, then the right root picked by box arithmetic. The imaginary unit is I(), the root of x² + 1 with positive imaginary part, and complex(x, y) builds x + iy from real parts.
A complex number of degree 2 is always (p + q√−m)/r, so it prints exactly: −2 + 2i, −1/2 + i√3/2. For higher degrees format computes the real and imaginary parts exactly and prints them in radicals when they have short forms, so ∛i comes out as √3/2 + i/2. Otherwise each part gets certified digits.
Principal roots
A non-zero number has n different n-th roots. The principal one is the one with the largest real part, the root whose angle is the original angle divided by n. For a negative real and even n two roots tie; the one with positive imaginary part wins, so √−4 = 2i.
The library finds it without angles or logarithms. If m is the minimal polynomial of z, every n-th root of z is a root of m(xⁿ). Those candidates are factored and isolated; interval powers decide which candidates have z itself as their n-th power (the others give z's conjugates), and box comparison picks the largest real part. The answer is exact: pow(nthRoot(z, 3), 3) equals z.
Odd roots of negative reals stay real by convention: root(-8, 3) is −2, not the principal complex root 1 + i√3.
In code
import { I, complex, sqrt, nthRoot, abs, re, im, format, roots } from "@ratmath/algebraic";
format(sqrt(complex(-3, 4))); // "1 + 2i"
format(nthRoot(I(), 3)); // "√3/2 + i/2"
format(abs(complex(1, 1))); // "√2"
re(complex(1, 2)).toRational(); // 1
const [, w] = roots([1, 1, 1], { complex: true }).map((r) => r.value);
w.toString(); // "−1/2 − i√3/2"
w.box(64); // { re: [lo, hi], im: [lo, hi] } as Core Rationals
@ratmath/algebraic and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.