Also, if you know that a polynomial division is exact then you can use "//" so as not to involve the fraction fields at all:
sage: R.<x,y>=QQ[] sage: (x^2-y^2)/(x-y) x + y sage: _.parent() Fraction Field of Multivariate Polynomial Ring in x, y over Rational Field sage: (x^2-y^2)//(x-y) x + y sage: _.parent() Multivariate Polynomial Ring in x, y over Rational Field John On Oct 24, 9:41 am, Simon King <[email protected]> wrote: > Hi Cary and John! > > On 24 Okt., 04:41, John H Palmieri <[email protected]> wrote: > > >... > > sage: R.<g17,g19> = PolynomialRing(QQ) > > sage: R.inject_variables() > > Note that inject_variables is not needed, because g17 annd g19 are > defined by the previous line anyway. > > > sage: p = (g17^2 - g19^2)/(g17 + g19) > > sage: type(p) > > <type 'sage.rings.fraction_field_element.FractionFieldElement'> > > sage: type(R(p)) > > <type > > 'sage.rings.polynomial.multi_polynomial_libsingular.MPolynomial_libsingular > > '> > > There is a faster way in this special case. > > Elements of the fraction field F of a ring R have methods > "numerator()" and "denominator()" that return elements of R. An > element of F is in R if and only if its denominator is one. For > example: > sage: R.<a,b,c> = ZZ[] > sage: p = R.random_element() > sage: q = p^2/p > sage: q.parent() > Fraction Field of Multivariate Polynomial Ring in a, b, c over Integer > Ring > sage: q.numerator().parent() > Multivariate Polynomial Ring in a, b, c over Integer Ring > sage: q.denominator() > 1 > > The aim is now to return an element of R that is equal to q, if this > happens to be possible. As John said, this can be done by attempting > an explicit conversion, by R(q). But apparently, if the denominator is > one, it can also be done by simply returning the numerator. > > The second solution is a lot faster: > sage: timeit('r=R(q)') > 625 loops, best of 3: 520 µs per loop > sage: timeit('r=q.numerator() if q.denominator()==1 else R(q)') > 625 loops, best of 3: 6.12 µs per loop > sage: p==q==R(q)==q.numerator() # verify that it is correct > True > > Note the detail "... else R(q)" above. This is in order to get a > proper error raised, in case that q really does not fit into R. > > By the way, I wonder why apparently there is no special case made for > fraction fields in the element constructor of R. Shouldn't there be a > ticket opened? > > Best regards, > Simon -- To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/sage-support URL: http://www.sagemath.org
