On Wed, May 5, 2010 at 2:46 PM, Matt Bainbridge
<bainbridge.m...@gmail.com> wrote:
> Sage knows how to coerce from Frac(ZZ[x]) to Frac(QQ[x]).  There is no
> coercion going the other way, though there should be one, since these
> two rings are equivalent.  Is there a reasonable way for me to define
> my own coercion?

This does it explicitly:

R.<x> = QQ[]
P.<y> = ZZ[]
a = 1/2*x + 3
b = 2/3*x^2 + 1
def convert(f):
    fn = f.numerator()
    fd = f.denominator()
    return (fn.numerator()*fd.denominator())/(fd.numerator()*fn.denominator())

sage: convert(f)
(3*x + 18)/(4*x^2 + 6)


If you want to do it implicitly, you can do the following at the very
beginning of the session:

R.<x> = QQ[]
P.<x> = ZZ[]
FR = Frac(R); FP = Frac(P)
sage: a = 1/2*x + 3
sage: b = 2/3*x^2 + 1
H = Hom(FR, FP)

def convert(f):
    fn = f.numerator()
    fd = f.denominator()
    return (fn.numerator()*fd.denominator())/(fd.numerator()*fn.denominator())

from sage.categories.morphism import SetMorphism
mor = SetMorphism(H, convert)
FP.register_coercion(mor)

After this, there are coercions in both directions so the parent
depends on the left operand:

sage: f = a/b
sage: f
(1/2*x + 3)/(2/3*x^2 + 1)
sage: f.parent()
Fraction Field of Univariate Polynomial Ring in x over Rational Field
sage: ff = convert(f)
sage: ff.parent()
Fraction Field of Univariate Polynomial Ring in x over Integer Ring

sage: (ff+f).parent()
Fraction Field of Univariate Polynomial Ring in x over Integer Ring
sage: (f+ff).parent()
Fraction Field of Univariate Polynomial Ring in x over Rational Field


But, you can always ask for it explicitly:

sage: FP(f+ff)
(3*x + 18)/(2*x^2 + 3)


--Mike

-- 
To post to this group, send email to sage-support@googlegroups.com
To unsubscribe from this group, send email to 
sage-support+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/sage-support
URL: http://www.sagemath.org

Reply via email to