Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

math - 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!

question from:https://stackoverflow.com/questions/65890347/python-sympy-common-denominator-to-symbolic-fraction

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...