Tuesday, 25 August 2020

Can Sympy simplify a rational expression by collecting multiple terms?

Given a rational expression E such as the one below, I'm looking to use Sympy to simplify it to something that looks like F (defined in the second block of Python code below):

import sympy as sp

a, b, c, d, n, t, A, B, C = sp.symbols('a, b, c, d, n, t, A, B, C', real = True)

E = n/(c-b) * ( B - (c-b)/(c-a)*A - (b-a)/(c-a)*B ) * (c-t)/(c-b) + n/(c-b) * ( (d-c)/(d-b)*B + (c-b)/(d-b)*C - B ) * (t-b)/(c-b)

print(sp.pretty( E ))
print(sp.pretty( E.simplify() ))

This prints

           ⎛     B⋅(-c + d)   C⋅(-b + c)⎞             ⎛  A⋅(-b + c)   B⋅(-a + b)    ⎞
n⋅(-b + t)⋅⎜-B + ────────── + ──────────⎟   n⋅(c - t)⋅⎜- ────────── - ────────── + B⎟
           ⎝       -b + d       -b + d  ⎠             ⎝    -a + c       -a + c      ⎠
───────────────────────────────────────── + ─────────────────────────────────────────
                        2                                           2                
                (-b + c)                                    (-b + c)
                
                
-n⋅((a - c)⋅(b - t)⋅(-B⋅(b - d) + B⋅(c - d) + C⋅(b - c)) + (b - d)⋅(c - t)⋅(A⋅(b - c) + B⋅(a - b) - B⋅(a - c))) 
────────────────────────────────────────────────────────────────────────────────────────────────────────────────
                                                           2                                                    
                                            (a - c)⋅(b - c) ⋅(b - d) 

However, the expression can be — manually — simplified further, the result of which I've labeled F:

F = n/(c-a) * (B - A) * (c-t)/(c-b) + n/(d-b) * (C - B) * (t-b)/(c-b)

print(sp.pretty( F ))
print((F-E).simplify())

This outputs

n⋅(-A + B)⋅(c - t)   n⋅(-B + C)⋅(-b + t)
────────────────── + ───────────────────
(-a + c)⋅(-b + c)     (-b + c)⋅(-b + d) 


0

I've looked into various options including factor(), collect() and apart(), but none of these seem to yield expressions that have the same structure as F. Any pointers on how to proceed?

Additionally, I wondered whether Sympy's pretty print function can be tweaked somehow to

  1. Keep the original order of the variables in both the numerator and denominator (e.g. B - A instead of -A + B). Currently the order is flipped in most cases, which looks rather ugly with the leading minus signs.
  2. Show composite fractions as products of simple fractions (e.g. a/b c/d instead of ac/bd), though in certain cases it can of course be ambiguous where/how to "split" such composite fractions.


from Can Sympy simplify a rational expression by collecting multiple terms?

No comments:

Post a Comment