简体   繁体   中英

python sympy common denominator to symbolic fraction

I want to generate a function that receive an expression with fractions (like A/(p+1)+B/(p+2) ), and return the common denominator fraction and pack the common part in the numerator (like ((A+B)p+2A+B)/((p+1)(p+2)) [the p taken out as a common multiples]).

There is a together function in sumpy that take the common denominator, but it does not pack the numerator.

How can I do that? Thanks!

After calling together you can use fraction to separate the numerator and denominator and then you can process the numerator with expand/collect :

In [38]: A, B, p = symbols('A, B, p')

In [39]: A/(p+1)+B/(p+2)
Out[39]: 
  A       B  
───── + ─────
p + 1   p + 2

In [40]: e = A/(p+1)+B/(p+2)

In [41]: together(e)
Out[41]: 
A⋅(p + 2) + B⋅(p + 1)
─────────────────────
   (p + 1)⋅(p + 2)   

In [42]: fraction(together(e))
Out[42]: (A⋅(p + 2) + B⋅(p + 1), (p + 1)⋅(p + 2))

In [43]: n, d = fraction(together(e))

In [44]: n = collect(expand(n), p)

In [45]: n/d
Out[45]: 
2⋅A + B + p⋅(A + B)
───────────────────
  (p + 1)⋅(p + 2)  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM