Skip to content

Commit e5c6aab

Browse files
author
Release Manager
committed
gh-37034: raise ValueError instead of IndexError in .any_root() 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: #37034 Reported by: Lorenz Panny Reviewer(s): Travis Scrimshaw
2 parents 5dc4e9a + d6660cd commit e5c6aab

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

src/sage/rings/polynomial/polynomial_element.pyx

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2159,6 +2159,14 @@ cdef class Polynomial(CommutativePolynomial):
21592159
sage: r = f.any_root()
21602160
sage: r^2 + r
21612161
a^2 + a
2162+
2163+
Check for :issue:`37034`::
2164+
2165+
sage: R.<x> = Zmod(55)[]
2166+
sage: (x^2 + 1).any_root()
2167+
Traceback (most recent call last):
2168+
...
2169+
ValueError: no roots (non-field) x^2 + 1
21622170
"""
21632171
if self.base_ring().is_finite() and self.base_ring().is_field():
21642172
if self.degree() < 0:
@@ -2312,7 +2320,10 @@ cdef class Polynomial(CommutativePolynomial):
23122320
else:
23132321
return (self//h).any_root(ring, -degree, True)
23142322
else:
2315-
return self.roots(ring=ring, multiplicities=False)[0]
2323+
rs = self.roots(ring=ring, multiplicities=False)
2324+
if rs:
2325+
return rs[0]
2326+
raise ValueError("no roots (non-field) %s" % self)
23162327

23172328
def __truediv__(left, right):
23182329
r"""

0 commit comments

Comments
 (0)