sagemath/sage

error when creating random polynomials

Closed this issue · 9 comments

The choose_degree option fails frequently.

sage: R.<x,y,z> = QQ[]
sage: set_random_seed(0)
sage: f = R.random_element(5, choose_degree=True)  # ok
sage: set_random_seed(1)
sage: f = R.random_element(5, choose_degree=True)  # fails
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-241bf39f07c2> in <module>
----> 1 f = R.random_element(Integer(5), choose_degree=True)

/usr/lib/python3.9/site-packages/sage/rings/polynomial/multi_polynomial_ring_base.pyx in sage.rings.polynomial.multi_polynomial_ring_base.MPolynomialRing_base.random_element (build/cythonized/sage/rings/polynomial/multi_polynomial_ring_base.c:14338)()
   1062             else:
   1063                 while terms:
-> 1064                     m = self._random_monomial_upto_degree_class(n, degree)
   1065                     if not m in M:
   1066                         M.add(m)

/usr/lib/python3.9/site-packages/sage/rings/polynomial/multi_polynomial_ring_base.pyx in sage.rings.polynomial.multi_polynomial_ring_base.MPolynomialRing_base._random_monomial_upto_degree_class (build/cythonized/sage/rings/polynomial/multi_polynomial_ring_base.c:12939)()
    874
    875         #Select random monomial of degree d
--> 876         random_index = ZZ.random_element(0, total-1)
    877         #Generate the corresponding monomial
    878         return self._to_monomial(random_index, n, d)

/usr/lib/python3.9/site-packages/sage/rings/integer_ring.pyx in sage.rings.integer_ring.IntegerRing_class.random_element (build/cythonized/sage/rings/integer_ring.c:6514)()
    715             raise TypeError("x must be > 0")
    716         if x is not None and y is not None and x >= y:
--> 717             raise TypeError("x must be < y")
    718         self._randomize_mpz(z.value, x, y, distribution)
    719         return z

TypeError: x must be < y

Component: commutative algebra

Author: Markus Wageringel

Branch/Commit: 7dfe75c

Reviewer: Samuel Lelièvre

Issue created by migration from https://trac.sagemath.org/ticket/31752

comment:1

Tested with Sage 9.2 and 9.3rc4.

Author: Markus Wageringel

comment:2

This is a simple off-by-one error. I have not added a doctest, as it will automatically be covered by #29979.


New commits:

7dfe75c31752: fix off-by-1 error creating random polynomials
slel commented

Reviewer: Samuel Lelièvre

slel commented
comment:3

I was coming to the same conclusion. The confusion was likely because

  • ZZ.random_element(a, b) includes a but excludes b,
  • similar to range(a, b) which works that way too,
  • but contrary to randint(a, b) which includes both a and b.
comment:4

Thanks.

Changed branch from u/gh-mwageringel/31752 to 7dfe75c