Skip to content

Commit

Permalink
sagemathgh-37034: raise ValueError instead of IndexError in .any_root()
Browse files Browse the repository at this point in the history
    
The `.any_root()` method sometimes raises an `IndexError` instead of the
usual `ValueError` when no root exists.

Example (Sage 10.2):
```sage
sage: R.<x> = Zmod(55)[]
sage: (x^2 + 1).any_root()
------------------------------------------------------------------------
---
IndexError                                Traceback (most recent call
last)
Cell In[2], line 1
----> 1 (x**Integer(2)+Integer(1)).any_root()

File /usr/lib/python3.11/site-
packages/sage/rings/polynomial/polynomial_element.pyx:2315, in
sage.rings.polynomial.polynomial_element.Polynomial.any_root
(build/cythonized/sage/rings/polynomial/polynomial_element.c:34795)()
   2313                         return (self//h).any_root(ring, -degree,
True)
   2314     else:
-> 2315         return self.roots(ring=ring, multiplicities=False)[0]
   2316
   2317 def __truediv__(left, right):

IndexError: list index out of range
```

With this patch, we check for the `IndexError` before it happens and
raise a `ValueError` instead.
    
URL: sagemath#37034
Reported by: Lorenz Panny
Reviewer(s): Travis Scrimshaw
  • Loading branch information
Release Manager committed Jan 16, 2024
2 parents 214c100 + d6660cd commit a3a5611
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/sage/rings/polynomial/polynomial_element.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -2159,6 +2159,14 @@ cdef class Polynomial(CommutativePolynomial):
sage: r = f.any_root()
sage: r^2 + r
a^2 + a
Check for :issue:`37034`::
sage: R.<x> = Zmod(55)[]
sage: (x^2 + 1).any_root()
Traceback (most recent call last):
...
ValueError: no roots (non-field) x^2 + 1
"""
if self.base_ring().is_finite() and self.base_ring().is_field():
if self.degree() < 0:
Expand Down Expand Up @@ -2312,7 +2320,10 @@ cdef class Polynomial(CommutativePolynomial):
else:
return (self//h).any_root(ring, -degree, True)
else:
return self.roots(ring=ring, multiplicities=False)[0]
rs = self.roots(ring=ring, multiplicities=False)
if rs:
return rs[0]
raise ValueError("no roots (non-field) %s" % self)

def __truediv__(left, right):
r"""
Expand Down

0 comments on commit a3a5611

Please sign in to comment.