Skip to content

panchi.symbolic

from panchi.symbolic import QuadraticNumber, sqrt, Polynomial, exact_roots, quadratic_roots

Exact numbers

panchi.symbolic.QuadraticNumber

An exact number of the form a + b√d with rational a and b.

The radicand d is a squarefree integer other than 0 and 1. A negative radicand makes the number complex: d = -1 is the imaginary unit i, so QuadraticNumber(3, -2, -1) is 3 - 2i. These numbers are closed under +, -, × and ÷ as long as every operand shares the same radicand, which is exactly what the eigenvalues of a 2×2 or 3×3 matrix need.

Arithmetic results whose √d part cancels collapse back to a plain int or Fraction, so exact computations stay as simple as possible.

Parameters:

Name Type Description Default
rational int | Fraction

The rational part a.

required
coefficient int | Fraction

The coefficient b of √d.

required
radicand int

The integer d under the square root. It is reduced to squarefree form, so QuadraticNumber(0, 1, 12) is stored as 2√3.

required

Raises:

Type Description
TypeError

If a or b is not an int or Fraction, or d is not an int.

ValueError

If d is a perfect square (including 0 and 1), since √d would then be rational.

Examples:

>>> golden = QuadraticNumber(Fraction(1, 2), Fraction(1, 2), 5)
>>> print(golden)
(1 + √5)/2
>>> golden * golden == golden + 1
True
>>> print(QuadraticNumber(1, 1, -1) * QuadraticNumber(1, -1, -1))
2
Source code in panchi/symbolic/quadratic_number.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
class QuadraticNumber:
    """
    An exact number of the form a + b√d with rational a and b.

    The radicand d is a squarefree integer other than 0 and 1. A negative
    radicand makes the number complex: d = -1 is the imaginary unit i, so
    ``QuadraticNumber(3, -2, -1)`` is 3 - 2i. These numbers are closed under
    +, -, × and ÷ as long as every operand shares the same radicand, which
    is exactly what the eigenvalues of a 2×2 or 3×3 matrix need.

    Arithmetic results whose √d part cancels collapse back to a plain int
    or Fraction, so exact computations stay as simple as possible.

    Parameters
    ----------
    rational : int | Fraction
        The rational part a.
    coefficient : int | Fraction
        The coefficient b of √d.
    radicand : int
        The integer d under the square root. It is reduced to squarefree
        form, so ``QuadraticNumber(0, 1, 12)`` is stored as 2√3.

    Raises
    ------
    TypeError
        If a or b is not an int or Fraction, or d is not an int.
    ValueError
        If d is a perfect square (including 0 and 1), since √d would
        then be rational.

    Examples
    --------
    >>> golden = QuadraticNumber(Fraction(1, 2), Fraction(1, 2), 5)
    >>> print(golden)
    (1 + √5)/2
    >>> golden * golden == golden + 1
    True
    >>> print(QuadraticNumber(1, 1, -1) * QuadraticNumber(1, -1, -1))
    2
    """

    def __init__(
        self, rational: Rational, coefficient: Rational, radicand: int
    ) -> None:
        for name, part in (("rational", rational), ("coefficient", coefficient)):
            if isinstance(part, bool) or not isinstance(part, (int, Fraction)):
                raise TypeError(
                    f"The {name} part of a QuadraticNumber must be an int or "
                    f"Fraction, but got {type(part).__name__}."
                )
        if isinstance(radicand, bool) or not isinstance(radicand, int):
            raise TypeError(
                f"The radicand of a QuadraticNumber must be an int, "
                f"but got {type(radicand).__name__}."
            )
        if radicand == 0:
            raise ValueError("The radicand cannot be 0, since √0 = 0 is rational.")
        square_root, squarefree = _squarefree_split(radicand)
        if squarefree == 1:
            raise ValueError(
                f"The radicand {radicand} is a perfect square, so √{radicand} "
                f"= {square_root} is rational. Use a plain int or Fraction."
            )
        self.rational = Fraction(rational)
        self.coefficient = Fraction(coefficient) * square_root
        self.radicand = squarefree

    def _parts(self, other: object) -> tuple[Fraction, Fraction] | None:
        """Return other as (a, b) over this radicand, or None if unsupported."""
        if isinstance(other, float):
            raise TypeError(
                "Cannot combine an exact QuadraticNumber with a float. "
                "Floats would destroy exactness; use int or Fraction values."
            )
        if isinstance(other, bool):
            return None
        if isinstance(other, (int, Fraction)):
            return Fraction(other), Fraction(0)
        if isinstance(other, QuadraticNumber):
            if other.coefficient != 0 and other.radicand != self.radicand:
                raise ValueError(
                    f"Cannot combine numbers involving √{self.radicand} and "
                    f"√{other.radicand}. A QuadraticNumber holds a single "
                    f"square root, so both operands must share the same radicand."
                )
            return other.rational, other.coefficient
        return None

    def __add__(self, other: object) -> Scalar:
        parts = self._parts(other)
        if parts is None:
            return NotImplemented
        a, b = parts
        return _make(self.rational + a, self.coefficient + b, self.radicand)

    __radd__ = __add__

    def __neg__(self) -> QuadraticNumber:
        return QuadraticNumber(-self.rational, -self.coefficient, self.radicand)

    def __pos__(self) -> QuadraticNumber:
        return self

    def __sub__(self, other: object) -> Scalar:
        parts = self._parts(other)
        if parts is None:
            return NotImplemented
        a, b = parts
        return _make(self.rational - a, self.coefficient - b, self.radicand)

    def __rsub__(self, other: object) -> Scalar:
        parts = self._parts(other)
        if parts is None:
            return NotImplemented
        a, b = parts
        return _make(a - self.rational, b - self.coefficient, self.radicand)

    def __mul__(self, other: object) -> Scalar:
        parts = self._parts(other)
        if parts is None:
            return NotImplemented
        a, b = parts
        return _make(
            self.rational * a + self.coefficient * b * self.radicand,
            self.rational * b + self.coefficient * a,
            self.radicand,
        )

    __rmul__ = __mul__

    def norm(self) -> Fraction:
        """
        Return the field norm (a + b√d)(a - b√d) = a² - d·b².

        The norm is always rational. For a complex number it is |z|².
        """
        return self.rational**2 - self.radicand * self.coefficient**2

    def conjugate(self) -> QuadraticNumber:
        """
        Return the conjugate a - b√d.

        For a complex number this is the usual complex conjugate.
        """
        return QuadraticNumber(self.rational, -self.coefficient, self.radicand)

    def _reciprocal(self) -> Scalar:
        norm = self.norm()
        if norm == 0:
            raise ZeroDivisionError("Cannot divide by zero.")
        return _make(self.rational / norm, -self.coefficient / norm, self.radicand)

    def __truediv__(self, other: object) -> Scalar:
        parts = self._parts(other)
        if parts is None:
            return NotImplemented
        a, b = parts
        if b == 0:
            if a == 0:
                raise ZeroDivisionError("Cannot divide by zero.")
            return _make(self.rational / a, self.coefficient / a, self.radicand)
        divisor = QuadraticNumber(a, b, self.radicand)
        return self * divisor._reciprocal()

    def __rtruediv__(self, other: object) -> Scalar:
        parts = self._parts(other)
        if parts is None:
            return NotImplemented
        a, b = parts
        return _make(a, b, self.radicand) * self._reciprocal()

    def __pow__(self, exponent: int) -> Scalar:
        if isinstance(exponent, bool) or not isinstance(exponent, int):
            return NotImplemented
        base: Scalar = self if exponent >= 0 else self._reciprocal()
        result: Scalar = 1
        for _ in range(abs(exponent)):
            result = result * base
        return result

    def __eq__(self, other: object) -> bool:
        if isinstance(other, bool):
            return False
        if isinstance(other, (int, Fraction)):
            return self.coefficient == 0 and self.rational == other
        if isinstance(other, QuadraticNumber):
            if self.coefficient == 0 and other.coefficient == 0:
                return self.rational == other.rational
            return (
                self.rational == other.rational
                and self.coefficient == other.coefficient
                and self.radicand == other.radicand
            )
        return NotImplemented

    def __hash__(self) -> int:
        if self.coefficient == 0:
            return hash(self.rational)
        return hash((self.rational, self.coefficient, self.radicand))

    def __bool__(self) -> bool:
        return self.rational != 0 or self.coefficient != 0

    @property
    def is_real(self) -> bool:
        """True when the number has no imaginary part."""
        return self.radicand > 0 or self.coefficient == 0

    @property
    def real(self) -> Scalar:
        """The real part, exactly."""
        if self.is_real:
            return self
        return _simplify(self.rational)

    @property
    def imag(self) -> Scalar:
        """The imaginary part, exactly (so the imaginary part of 1 + i√2 is √2)."""
        if self.is_real:
            return 0
        imaginary = self.coefficient * sqrt(-self.radicand)
        return _simplify(imaginary)

    def _sign(self) -> int:
        """Return -1, 0 or 1 for a real number, using exact comparison."""
        a_sign = (self.rational > 0) - (self.rational < 0)
        b_sign = (self.coefficient > 0) - (self.coefficient < 0)
        if a_sign == b_sign or b_sign == 0:
            return a_sign
        if a_sign == 0:
            return b_sign
        rational_square = self.rational**2
        radical_square = self.coefficient**2 * self.radicand
        if rational_square > radical_square:
            return a_sign
        if rational_square < radical_square:
            return b_sign
        return 0

    def _compare(self, other: object) -> int | None:
        """Return the sign of self - other, or None if unsupported."""
        if not self.is_real:
            raise TypeError(
                f"Cannot order the complex number {self}. "
                f"Only real numbers can be compared with <, <=, > or >=."
            )
        if isinstance(other, float):
            if other == 0:
                return self._sign()
            approximation = float(self)
            return (approximation > other) - (approximation < other)
        difference = self - other
        if difference is NotImplemented:
            return None
        if isinstance(difference, QuadraticNumber):
            if not difference.is_real:
                raise TypeError(
                    f"Cannot order {self} against the complex number {other}."
                )
            return difference._sign()
        return (difference > 0) - (difference < 0)

    def __lt__(self, other: object) -> bool:
        sign = self._compare(other)
        return NotImplemented if sign is None else sign < 0

    def __le__(self, other: object) -> bool:
        sign = self._compare(other)
        return NotImplemented if sign is None else sign <= 0

    def __gt__(self, other: object) -> bool:
        sign = self._compare(other)
        return NotImplemented if sign is None else sign > 0

    def __ge__(self, other: object) -> bool:
        sign = self._compare(other)
        return NotImplemented if sign is None else sign >= 0

    def __abs__(self) -> Scalar:
        """
        Return the exact absolute value (the modulus, for complex numbers).

        For a complex number this is √(a² - d·b²), which may involve a
        different square root than the number itself.
        """
        if self.is_real:
            return -self if self._sign() < 0 else self
        return sqrt(self.norm())

    def __float__(self) -> float:
        if not self.is_real:
            raise TypeError(
                f"Cannot convert the complex number {self} to a float. "
                f"Use complex() instead."
            )
        return float(self.rational) + float(self.coefficient) * self.radicand**0.5

    def __complex__(self) -> complex:
        if self.is_real:
            return complex(float(self))
        return complex(
            float(self.rational),
            float(self.coefficient) * (-self.radicand) ** 0.5,
        )

    def _integer_parts(self) -> tuple[int, int, int]:
        """Return (A, B, L) with a + b√d = (A + B√d) / L over a common denominator."""
        denominator = lcm(self.rational.denominator, self.coefficient.denominator)
        return (
            int(self.rational * denominator),
            int(self.coefficient * denominator),
            denominator,
        )

    def _radical_term(self, magnitude: int, latex: bool) -> str:
        """Render |B|·√|d| (with i for complex numbers) for a positive magnitude."""
        prefix = "" if magnitude == 1 else str(magnitude)
        root = abs(self.radicand)
        imaginary = "i" if self.radicand < 0 else ""
        if root == 1:
            return f"{prefix}{imaginary}"
        radical = f"\\sqrt{{{root}}}" if latex else f"√{root}"
        return f"{prefix}{imaginary}{radical}"

    def _render(self, latex: bool) -> str:
        if self.coefficient == 0:
            return str(_simplify(self.rational))
        whole, radical_coefficient, denominator = self._integer_parts()
        radical = self._radical_term(abs(radical_coefficient), latex)
        if whole == 0:
            sign = "-" if radical_coefficient < 0 else ""
            if denominator == 1:
                return f"{sign}{radical}"
            if latex:
                return f"{sign}\\frac{{{radical}}}{{{denominator}}}"
            return f"{sign}{radical}/{denominator}"
        operator = "-" if radical_coefficient < 0 else "+"
        numerator = f"{whole} {operator} {radical}"
        if denominator == 1:
            return numerator
        if latex:
            return f"\\frac{{{numerator}}}{{{denominator}}}"
        return f"({numerator})/{denominator}"

    def __str__(self) -> str:
        """
        Return the number in standard mathematical form.

        Examples
        --------
        >>> print(QuadraticNumber(Fraction(1, 2), Fraction(1, 2), 5))
        (1 + √5)/2
        >>> print(QuadraticNumber(1, -2, -3))
        1 - 2i√3
        """
        return self._render(latex=False)

    def __repr__(self) -> str:
        return (
            f"QuadraticNumber({_simplify(self.rational)!r}, "
            f"{_simplify(self.coefficient)!r}, "
            f"{self.radicand})"
        )

    def _latex(self) -> str:
        """Render the number as a LaTeX fragment (no math delimiters)."""
        return self._render(latex=True)

    def _repr_latex_(self) -> str:
        return f"${self._latex()}$"

imag property

The imaginary part, exactly (so the imaginary part of 1 + i√2 is √2).

is_real property

True when the number has no imaginary part.

real property

The real part, exactly.

__abs__()

Return the exact absolute value (the modulus, for complex numbers).

For a complex number this is √(a² - d·b²), which may involve a different square root than the number itself.

Source code in panchi/symbolic/quadratic_number.py
367
368
369
370
371
372
373
374
375
376
def __abs__(self) -> Scalar:
    """
    Return the exact absolute value (the modulus, for complex numbers).

    For a complex number this is √(a² - d·b²), which may involve a
    different square root than the number itself.
    """
    if self.is_real:
        return -self if self._sign() < 0 else self
    return sqrt(self.norm())

__str__()

Return the number in standard mathematical form.

Examples:

>>> print(QuadraticNumber(Fraction(1, 2), Fraction(1, 2), 5))
(1 + √5)/2
>>> print(QuadraticNumber(1, -2, -3))
1 - 2i√3
Source code in panchi/symbolic/quadratic_number.py
433
434
435
436
437
438
439
440
441
442
443
444
def __str__(self) -> str:
    """
    Return the number in standard mathematical form.

    Examples
    --------
    >>> print(QuadraticNumber(Fraction(1, 2), Fraction(1, 2), 5))
    (1 + √5)/2
    >>> print(QuadraticNumber(1, -2, -3))
    1 - 2i√3
    """
    return self._render(latex=False)

conjugate()

Return the conjugate a - b√d.

For a complex number this is the usual complex conjugate.

Source code in panchi/symbolic/quadratic_number.py
227
228
229
230
231
232
233
def conjugate(self) -> QuadraticNumber:
    """
    Return the conjugate a - b√d.

    For a complex number this is the usual complex conjugate.
    """
    return QuadraticNumber(self.rational, -self.coefficient, self.radicand)

norm()

Return the field norm (a + b√d)(a - b√d) = a² - d·b².

The norm is always rational. For a complex number it is |z|².

Source code in panchi/symbolic/quadratic_number.py
219
220
221
222
223
224
225
def norm(self) -> Fraction:
    """
    Return the field norm (a + b√d)(a - b√d) = a² - d·b².

    The norm is always rational. For a complex number it is |z|².
    """
    return self.rational**2 - self.radicand * self.coefficient**2

panchi.symbolic.sqrt(value)

Return the exact square root of a rational number.

Perfect squares give an int or Fraction. Anything else gives a QuadraticNumber in simplest radical form, so sqrt(12) is 2√3. Negative values give imaginary results, so sqrt(-4) is 2i.

Parameters:

Name Type Description Default
value int | Fraction

The rational number whose square root to take.

required

Returns:

Type Description
int | Fraction | QuadraticNumber

The exact square root.

Raises:

Type Description
TypeError

If value is not an int or Fraction.

Examples:

>>> sqrt(9)
3
>>> print(sqrt(8))
2√2
>>> print(sqrt(Fraction(1, 2)))
√2/2
>>> print(sqrt(-1))
i
Source code in panchi/symbolic/quadratic_number.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def sqrt(value: Rational) -> Rational | QuadraticNumber:
    """
    Return the exact square root of a rational number.

    Perfect squares give an int or Fraction. Anything else gives a
    QuadraticNumber in simplest radical form, so ``sqrt(12)`` is ``2√3``.
    Negative values give imaginary results, so ``sqrt(-4)`` is ``2i``.

    Parameters
    ----------
    value : int | Fraction
        The rational number whose square root to take.

    Returns
    -------
    int | Fraction | QuadraticNumber
        The exact square root.

    Raises
    ------
    TypeError
        If value is not an int or Fraction.

    Examples
    --------
    >>> sqrt(9)
    3
    >>> print(sqrt(8))
    2√2
    >>> print(sqrt(Fraction(1, 2)))
    √2/2
    >>> print(sqrt(-1))
    i
    """
    if isinstance(value, bool) or not isinstance(value, (int, Fraction)):
        raise TypeError(
            f"sqrt() needs an exact rational number (int or Fraction), "
            f"but got {type(value).__name__}. "
            f"Floats cannot be square-rooted exactly."
        )
    value = Fraction(value)
    if value == 0:
        return 0
    denominator = value.denominator
    square_root, radicand = _squarefree_split(value.numerator * denominator)
    coefficient = Fraction(square_root, denominator)
    if radicand == 1:
        return _simplify(coefficient)
    return QuadraticNumber(0, coefficient, radicand)

Polynomials

panchi.symbolic.Polynomial

A polynomial in one variable with exact coefficients.

Coefficients are listed from the constant term upwards, so Polynomial([6, -5, 1]) is λ² - 5λ + 6. Coefficients may be ints, Fractions or QuadraticNumbers, and trailing zero coefficients are dropped.

Parameters:

Name Type Description Default
coefficients list[int | Fraction | QuadraticNumber]

The coefficients, constant term first.

required
variable str

The name of the variable used when printing. Defaults to "λ".

'λ'

Raises:

Type Description
TypeError

If any coefficient is not an exact number.

Examples:

>>> p = Polynomial([6, -5, 1])
>>> print(p)
λ² - 5λ + 6
>>> p(2)
0
Source code in panchi/symbolic/polynomial.py
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
class Polynomial:
    """
    A polynomial in one variable with exact coefficients.

    Coefficients are listed from the constant term upwards, so
    ``Polynomial([6, -5, 1])`` is λ² - 5λ + 6. Coefficients may be ints,
    Fractions or QuadraticNumbers, and trailing zero coefficients are
    dropped.

    Parameters
    ----------
    coefficients : list[int | Fraction | QuadraticNumber]
        The coefficients, constant term first.
    variable : str, optional
        The name of the variable used when printing. Defaults to "λ".

    Raises
    ------
    TypeError
        If any coefficient is not an exact number.

    Examples
    --------
    >>> p = Polynomial([6, -5, 1])
    >>> print(p)
    λ² - 5λ + 6
    >>> p(2)
    0
    """

    def __init__(self, coefficients: list[Scalar], variable: str = "λ") -> None:
        for c in coefficients:
            if isinstance(c, bool) or not isinstance(
                c, (int, Fraction, QuadraticNumber)
            ):
                raise TypeError(
                    f"Polynomial coefficients must be exact numbers (int, "
                    f"Fraction or QuadraticNumber), but got {type(c).__name__}."
                )
        trimmed = list(coefficients)
        while len(trimmed) > 1 and trimmed[-1] == 0:
            trimmed.pop()
        self.coefficients: list[Scalar] = trimmed or [0]
        self.variable = variable

    @property
    def degree(self) -> int:
        """The highest power with a non-zero coefficient (0 for constants)."""
        return len(self.coefficients) - 1

    @property
    def leading_coefficient(self) -> Scalar:
        """The coefficient of the highest power."""
        return self.coefficients[-1]

    def _coerce(self, other: object) -> Polynomial | None:
        if isinstance(other, Polynomial):
            return other
        if isinstance(other, bool):
            return None
        if isinstance(other, (int, Fraction, QuadraticNumber)):
            return Polynomial([other], self.variable)
        return None

    def __add__(self, other: object) -> Polynomial:
        other_poly = self._coerce(other)
        if other_poly is None:
            return NotImplemented
        size = max(len(self.coefficients), len(other_poly.coefficients))
        mine = self.coefficients + [0] * (size - len(self.coefficients))
        theirs = other_poly.coefficients + [0] * (size - len(other_poly.coefficients))
        return Polynomial(
            [a + b for a, b in zip(mine, theirs, strict=True)], self.variable
        )

    __radd__ = __add__

    def __neg__(self) -> Polynomial:
        return Polynomial([-c for c in self.coefficients], self.variable)

    def __sub__(self, other: object) -> Polynomial:
        other_poly = self._coerce(other)
        if other_poly is None:
            return NotImplemented
        return self + (-other_poly)

    def __rsub__(self, other: object) -> Polynomial:
        other_poly = self._coerce(other)
        if other_poly is None:
            return NotImplemented
        return other_poly + (-self)

    def __mul__(self, other: object) -> Polynomial:
        other_poly = self._coerce(other)
        if other_poly is None:
            return NotImplemented
        product: list[Scalar] = [0] * (
            len(self.coefficients) + len(other_poly.coefficients) - 1
        )
        for i, a in enumerate(self.coefficients):
            for j, b in enumerate(other_poly.coefficients):
                product[i + j] = product[i + j] + a * b
        return Polynomial(product, self.variable)

    __rmul__ = __mul__

    def __call__(self, value: Scalar) -> Scalar:
        """
        Evaluate the polynomial at a value using Horner's method.

        Examples
        --------
        >>> Polynomial([6, -5, 1])(3)
        0
        """
        result: Scalar = 0
        for c in reversed(self.coefficients):
            result = result * value + c
        return result

    def __eq__(self, other: object) -> bool:
        other_poly = self._coerce(other)
        if other_poly is None:
            return NotImplemented
        return self.coefficients == other_poly.coefficients

    def __hash__(self) -> int:
        return hash(tuple(self.coefficients))

    def divide_by_root(self, root: Scalar) -> tuple[Polynomial, Scalar]:
        """
        Divide by (λ - root) using synthetic division.

        Parameters
        ----------
        root : int | Fraction | QuadraticNumber
            The value r in the divisor (λ - r).

        Returns
        -------
        tuple[Polynomial, Scalar]
            The quotient and the remainder. The remainder is zero exactly
            when root is a root of the polynomial.

        Examples
        --------
        >>> quotient, remainder = Polynomial([6, -5, 1]).divide_by_root(2)
        >>> print(quotient)
        λ - 3
        >>> remainder
        0
        """
        running: Scalar = 0
        quotient: list[Scalar] = []
        for c in reversed(self.coefficients):
            running = running * root + c
            quotient.append(running)
        remainder = quotient.pop()
        quotient.reverse()
        return Polynomial(quotient or [0], self.variable), remainder

    def rational_roots(self) -> list[Rational]:
        """
        Find every rational root using the rational root theorem.

        After clearing denominators, any rational root p/q in lowest terms
        has p dividing the constant term and q dividing the leading
        coefficient, so only finitely many candidates need checking.

        Returns
        -------
        list[int | Fraction]
            The distinct rational roots, in increasing order.

        Raises
        ------
        TypeError
            If any coefficient is irrational or complex.

        Examples
        --------
        >>> Polynomial([-6, 11, -6, 1]).rational_roots()
        [1, 2, 3]
        """
        if any(isinstance(c, QuadraticNumber) for c in self.coefficients):
            raise TypeError(
                "The rational root theorem only applies to polynomials with "
                "rational coefficients."
            )
        if self.degree == 0:
            return []
        scale = lcm(*(Fraction(c).denominator for c in self.coefficients))
        integers = [int(c * scale) for c in self.coefficients]

        roots: list[Rational] = []
        lowest = 0
        while integers[lowest] == 0:
            lowest += 1
        if lowest > 0:
            roots.append(0)
        integers = integers[lowest:]
        if len(integers) == 1:
            return roots

        candidates = set()
        for p in _divisors(integers[0]):
            for q in _divisors(integers[-1]):
                candidates.add(Fraction(p, q))
                candidates.add(Fraction(-p, q))
        shifted = Polynomial(integers, self.variable)
        for candidate in sorted(candidates):
            if shifted(candidate) == 0:
                roots.append(_simplify(candidate))
        return sorted(roots)

    def _term(self, power: int, latex: bool) -> str:
        variable = (
            _LATEX_VARIABLES.get(self.variable, self.variable)
            if latex
            else self.variable
        )
        if power == 0:
            return ""
        if power == 1:
            return variable
        if latex:
            return f"{variable}^{{{power}}}"
        return f"{variable}{str(power).translate(_SUPERSCRIPTS)}"

    def _coefficient_text(self, value: Scalar, latex: bool) -> str:
        if latex:
            return scalar_to_latex(value)
        return str(value)

    def _render(self, latex: bool) -> str:
        pieces: list[str] = []
        for power in range(self.degree, -1, -1):
            c = self.coefficients[power]
            if c == 0 and self.degree > 0:
                continue
            term = self._term(power, latex)
            if isinstance(c, QuadraticNumber):
                text = self._coefficient_text(c, latex)
                sign, body = "+", f"({text})" if term else text
            else:
                sign = "-" if c < 0 else "+"
                magnitude = abs(c)
                body = (
                    ""
                    if magnitude == 1 and term
                    else self._coefficient_text(magnitude, latex)
                )
                if term and not latex and "/" in body:
                    body = f"({body})"
            pieces.append(sign)
            pieces.append(f"{body}{term}")
        first_sign, first_body = pieces[0], pieces[1]
        text = ("-" if first_sign == "-" else "") + first_body
        for i in range(2, len(pieces), 2):
            text += f" {pieces[i]} {pieces[i + 1]}"
        return text

    def __str__(self) -> str:
        """
        Return the polynomial written from the highest power down.

        Examples
        --------
        >>> print(Polynomial([-2, 0, 0, 1]))
        λ³ - 2
        """
        return self._render(latex=False)

    def __repr__(self) -> str:
        return f"Polynomial({self.coefficients!r})"

    def _latex(self) -> str:
        """Render the polynomial as a LaTeX fragment (no math delimiters)."""
        return self._render(latex=True)

    def _repr_latex_(self) -> str:
        return f"${self._latex()}$"

degree property

The highest power with a non-zero coefficient (0 for constants).

leading_coefficient property

The coefficient of the highest power.

__call__(value)

Evaluate the polynomial at a value using Horner's method.

Examples:

>>> Polynomial([6, -5, 1])(3)
0
Source code in panchi/symbolic/polynomial.py
135
136
137
138
139
140
141
142
143
144
145
146
147
def __call__(self, value: Scalar) -> Scalar:
    """
    Evaluate the polynomial at a value using Horner's method.

    Examples
    --------
    >>> Polynomial([6, -5, 1])(3)
    0
    """
    result: Scalar = 0
    for c in reversed(self.coefficients):
        result = result * value + c
    return result

__str__()

Return the polynomial written from the highest power down.

Examples:

>>> print(Polynomial([-2, 0, 0, 1]))
λ³ - 2
Source code in panchi/symbolic/polynomial.py
291
292
293
294
295
296
297
298
299
300
def __str__(self) -> str:
    """
    Return the polynomial written from the highest power down.

    Examples
    --------
    >>> print(Polynomial([-2, 0, 0, 1]))
    λ³ - 2
    """
    return self._render(latex=False)

divide_by_root(root)

Divide by (λ - root) using synthetic division.

Parameters:

Name Type Description Default
root int | Fraction | QuadraticNumber

The value r in the divisor (λ - r).

required

Returns:

Type Description
tuple[Polynomial, Scalar]

The quotient and the remainder. The remainder is zero exactly when root is a root of the polynomial.

Examples:

>>> quotient, remainder = Polynomial([6, -5, 1]).divide_by_root(2)
>>> print(quotient)
λ - 3
>>> remainder
0
Source code in panchi/symbolic/polynomial.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
def divide_by_root(self, root: Scalar) -> tuple[Polynomial, Scalar]:
    """
    Divide by (λ - root) using synthetic division.

    Parameters
    ----------
    root : int | Fraction | QuadraticNumber
        The value r in the divisor (λ - r).

    Returns
    -------
    tuple[Polynomial, Scalar]
        The quotient and the remainder. The remainder is zero exactly
        when root is a root of the polynomial.

    Examples
    --------
    >>> quotient, remainder = Polynomial([6, -5, 1]).divide_by_root(2)
    >>> print(quotient)
    λ - 3
    >>> remainder
    0
    """
    running: Scalar = 0
    quotient: list[Scalar] = []
    for c in reversed(self.coefficients):
        running = running * root + c
        quotient.append(running)
    remainder = quotient.pop()
    quotient.reverse()
    return Polynomial(quotient or [0], self.variable), remainder

rational_roots()

Find every rational root using the rational root theorem.

After clearing denominators, any rational root p/q in lowest terms has p dividing the constant term and q dividing the leading coefficient, so only finitely many candidates need checking.

Returns:

Type Description
list[int | Fraction]

The distinct rational roots, in increasing order.

Raises:

Type Description
TypeError

If any coefficient is irrational or complex.

Examples:

>>> Polynomial([-6, 11, -6, 1]).rational_roots()
[1, 2, 3]
Source code in panchi/symbolic/polynomial.py
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def rational_roots(self) -> list[Rational]:
    """
    Find every rational root using the rational root theorem.

    After clearing denominators, any rational root p/q in lowest terms
    has p dividing the constant term and q dividing the leading
    coefficient, so only finitely many candidates need checking.

    Returns
    -------
    list[int | Fraction]
        The distinct rational roots, in increasing order.

    Raises
    ------
    TypeError
        If any coefficient is irrational or complex.

    Examples
    --------
    >>> Polynomial([-6, 11, -6, 1]).rational_roots()
    [1, 2, 3]
    """
    if any(isinstance(c, QuadraticNumber) for c in self.coefficients):
        raise TypeError(
            "The rational root theorem only applies to polynomials with "
            "rational coefficients."
        )
    if self.degree == 0:
        return []
    scale = lcm(*(Fraction(c).denominator for c in self.coefficients))
    integers = [int(c * scale) for c in self.coefficients]

    roots: list[Rational] = []
    lowest = 0
    while integers[lowest] == 0:
        lowest += 1
    if lowest > 0:
        roots.append(0)
    integers = integers[lowest:]
    if len(integers) == 1:
        return roots

    candidates = set()
    for p in _divisors(integers[0]):
        for q in _divisors(integers[-1]):
            candidates.add(Fraction(p, q))
            candidates.add(Fraction(-p, q))
    shifted = Polynomial(integers, self.variable)
    for candidate in sorted(candidates):
        if shifted(candidate) == 0:
            roots.append(_simplify(candidate))
    return sorted(roots)

Root finding

panchi.symbolic.exact_roots(polynomial)

Find every root of a polynomial exactly, with multiplicities.

Rational roots are found with the rational root theorem and divided out by synthetic division, repeatedly, so repeated roots are counted. Whatever remains must have degree at most 2, which is then solved with the quadratic formula. This is the by-hand method for characteristic polynomials of 2×2 and 3×3 matrices.

Parameters:

Name Type Description Default
polynomial Polynomial

A non-constant polynomial with rational coefficients.

required

Returns:

Type Description
list[tuple[Scalar, int]]

The distinct roots paired with their multiplicities, real roots first in increasing order, then complex ones.

Raises:

Type Description
ValueError

If the polynomial is constant, or if after removing rational roots a factor of degree 3 or more remains (for example λ³ - 2, whose roots involve cube roots and cannot be written as a + b√d).

Examples:

>>> [(str(r), m) for r, m in exact_roots(Polynomial([-4, 8, -5, 1]))]
[('1', 1), ('2', 2)]
Source code in panchi/symbolic/roots.py
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
def exact_roots(polynomial: Polynomial) -> list[tuple[Scalar, int]]:
    """
    Find every root of a polynomial exactly, with multiplicities.

    Rational roots are found with the rational root theorem and divided
    out by synthetic division, repeatedly, so repeated roots are counted.
    Whatever remains must have degree at most 2, which is then solved with
    the quadratic formula. This is the by-hand method for characteristic
    polynomials of 2×2 and 3×3 matrices.

    Parameters
    ----------
    polynomial : Polynomial
        A non-constant polynomial with rational coefficients.

    Returns
    -------
    list[tuple[Scalar, int]]
        The distinct roots paired with their multiplicities, real roots
        first in increasing order, then complex ones.

    Raises
    ------
    ValueError
        If the polynomial is constant, or if after removing rational roots
        a factor of degree 3 or more remains (for example λ³ - 2, whose
        roots involve cube roots and cannot be written as a + b√d).

    Examples
    --------
    >>> [(str(r), m) for r, m in exact_roots(Polynomial([-4, 8, -5, 1]))]
    [('1', 1), ('2', 2)]
    """
    if polynomial.degree < 1:
        raise ValueError(f"A constant polynomial ({polynomial}) has no roots to find.")
    multiplicities: dict[Scalar, int] = {}
    remaining = polynomial
    for root in polynomial.rational_roots():
        while remaining.degree > 0:
            quotient, remainder = remaining.divide_by_root(root)
            if remainder != 0:
                break
            multiplicities[root] = multiplicities.get(root, 0) + 1
            remaining = quotient

    if remaining.degree == 1:
        constant, slope = remaining.coefficients
        root = _simplify(Fraction(-constant) / slope)
        multiplicities[root] = multiplicities.get(root, 0) + 1
    elif remaining.degree == 2:
        for root, count in quadratic_roots(remaining):
            multiplicities[root] = multiplicities.get(root, 0) + count
    elif remaining.degree > 2:
        if remaining == polynomial:
            reason = "It has no rational roots"
        else:
            reason = (
                f"After removing its rational roots, the factor {remaining} "
                f"is left, which has no rational roots"
            )
        raise ValueError(
            f"Cannot find the roots of {polynomial} exactly. {reason}, so its "
            f"roots involve cube roots (or worse) and cannot be written in "
            f"the form a + b√d."
        )
    return sorted(multiplicities.items(), key=lambda pair: _root_order(pair[0]))

panchi.symbolic.quadratic_roots(polynomial)

Solve a quadratic exactly with the quadratic formula.

For aλ² + bλ + c the roots are (-b ± √(b² - 4ac)) / 2a. The discriminant b² - 4ac decides their kind: a perfect square gives rational roots, any other positive value gives irrational ones such as 1 ± √2, a negative value gives a complex conjugate pair, and zero gives a single repeated root.

Parameters:

Name Type Description Default
polynomial Polynomial

A degree-2 polynomial with rational coefficients.

required

Returns:

Type Description
list[tuple[Scalar, int]]

The distinct roots paired with their multiplicities.

Raises:

Type Description
ValueError

If the polynomial is not quadratic.

Examples:

>>> [(str(r), m) for r, m in quadratic_roots(Polynomial([1, -2, 1]))]
[('1', 2)]
>>> [str(r) for r, _ in quadratic_roots(Polynomial([2, -2, 1]))]
['1 - i', '1 + i']
Source code in panchi/symbolic/roots.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def quadratic_roots(polynomial: Polynomial) -> list[tuple[Scalar, int]]:
    """
    Solve a quadratic exactly with the quadratic formula.

    For aλ² + bλ + c the roots are (-b ± √(b² - 4ac)) / 2a. The
    discriminant b² - 4ac decides their kind: a perfect square gives
    rational roots, any other positive value gives irrational ones such
    as 1 ± √2, a negative value gives a complex conjugate pair, and zero
    gives a single repeated root.

    Parameters
    ----------
    polynomial : Polynomial
        A degree-2 polynomial with rational coefficients.

    Returns
    -------
    list[tuple[Scalar, int]]
        The distinct roots paired with their multiplicities.

    Raises
    ------
    ValueError
        If the polynomial is not quadratic.

    Examples
    --------
    >>> [(str(r), m) for r, m in quadratic_roots(Polynomial([1, -2, 1]))]
    [('1', 2)]
    >>> [str(r) for r, _ in quadratic_roots(Polynomial([2, -2, 1]))]
    ['1 - i', '1 + i']
    """
    if polynomial.degree != 2:
        raise ValueError(
            f"quadratic_roots() needs a degree-2 polynomial, but {polynomial} "
            f"has degree {polynomial.degree}."
        )
    c, b, a = polynomial.coefficients
    discriminant = b * b - 4 * a * c
    if discriminant == 0:
        return [(_simplify(-b / Fraction(2 * a)), 2)]
    root = sqrt(discriminant)
    roots = [(-b - root) / (2 * a), (-b + root) / (2 * a)]
    roots = [_simplify(r) for r in roots]
    return [(r, 1) for r in sorted(roots, key=_root_order)]