Simplifying numerator

I'm writing a script to create quotient rule exercises, but I cannot coerce the fraction to simplify as desired. In particular, I'd like latex(sol) to look like the following:

 \frac{2x+4}{(x^2+1)^2} 

But evaluating

 (2*x+4)/(x^2+1)^2 

always seems to factor the numerator to get

 2*(x + 2)/(x^2 + 1)^2 

and simplify_full() seems to only expand the denominator, not the numerator:

 2*(x + 2)/(x^4 + 2*x^2 + 1) 

For clarity, I think the general problem is this (perhaps?) surprising phenomenon: latex(f/g) doesn't seem to respect whether the expression f is factored or not.

edit retag close merge delete

Sort by ยป oldest newest most voted

Hello, @StevenClontz! I don't know if this solves the general case of your question, but it does solve the particular example your present. Write the following:

def latex_frac(frac):
if frac == 0:    return '0'
num = frac.numerator()
den = frac.denominator()
if den == 1:    return str(num)
return r'\frac{' + str(num) + '}{' + str(den) + '}'


You can then call this functions like this:

latex_frac((2*x+4)/(x^2+1)^2)


which will give the result you want.

I hope this helps!

more

Thanks for the reply! I was trying to use the sage standard library to solve this, but you're correct, it'd be pretty easy to write a custom function to do what I need in this narrow case. I'm editing the original question to make this clearer.

( 2020-06-03 14:08:56 -0500 )edit

Not strictly true :

sage: ((2*x+4)/(x^2+1)^2).expand()
2*x/(x^4 + 2*x^2 + 1) + 4/(x^4 + 2*x^2 + 1)


But :

sage: ((2*x+4)/(x^2+1)^2).expand().factor()
2*(x + 2)/(x^2 + 1)^2
sage: ((2*x+4)/(x^2+1)^2).expand().combine()
2*(x + 2)/(x^4 + 2*x^2 + 1)


Note that :

sage: ((2*x+4)/(x^2+1)^2).expand().simplify()
2*x/(x^4 + 2*x^2 + 1) + 4/(x^4 + 2*x^2 + 1)


But that :

sage: ((2*x+4)/(x^2+1)^2).expand().simplify_full()
2*(x + 2)/(x^4 + 2*x^2 + 1)


Sorry.

This is general :

sage: var("a")
a
sage: a*(2*x+4)
2*a*(x + 2)


PS : I fail to see the point...

more