r/learnpython • • 3h ago

How can I get sympy to output functions as their rational form?

Sorry this isn't super specific to python, but I can't find anything online. I want to specify to sympy that I want the output of its simplification to be in the form of a rational function. (A rational function is one where it equals one polynomial divided by another.)

After the function gets complex enough, it does start to format it as a rational function (but not exactly, it does factoring where it can). I want the output to be in the format of

(x0 * (a^n0*b^m0) + x1 * (a^n1*b^m1) + ...) / (X0 * (a^N0*b^M0) + X1 * (a^N1*b^M0) + ...)

where the powers and coefficients are integers.

It's not super relevant, but here is my code:

def f(a, b):
    return 1 - a/b


a = s.Symbol('a', real=True)
eq_1 = s.simplify(f(a, s.Symbol('b', real=True)))
eq_2 = s.simplify(f(eq_1, a))


i = 3
while True:
    old_eq = eq_2
    eq_2   = s.simplify(f(eq_2, eq_1))
    eq_1 = old_eq
    print(f'f({i}) = {s.latex(eq_2)}\n')

    i += 1
41 Upvotes

2 comments sorted by

2

u/Explorer651 2h ago

Try sympy's cancel instead of simplify. The SymPy tutorial says it puts a rational function into the canonical form p over q, where p and q are expanded polynomials with no common factors, so you shouldn't get the leftover factoring.

1

u/playsthebongcloud 2h ago

Thanks! That's exactly what I wanted. Sympy even solves it faster now, which I didn't expect.