I have found this annoying problem in sympy. I want to simply the following simple fraction expression below but can't make it work... Sympy even recognizes the two equations as equal making it even more frustrating.
import sympy as sp
a,b,c,d = sp.symbols('a, b, c, d', positive = True)
expr = (a*b*c+2*d*a*c+b*c*d)/(2*a+b)
correct_simpl = c*(d + a*b/(2*a+b))
display(expr)
display(expr.simplify())
display(correct_simpl)
correct_simpl.equals(expr)
Returns:
I have found this annoying problem in sympy. I want to simply the following simple fraction expression below but can't make it work... Sympy even recognizes the two equations as equal making it even more frustrating.
import sympy as sp
a,b,c,d = sp.symbols('a, b, c, d', positive = True)
expr = (a*b*c+2*d*a*c+b*c*d)/(2*a+b)
correct_simpl = c*(d + a*b/(2*a+b))
display(expr)
display(expr.simplify())
display(correct_simpl)
correct_simpl.equals(expr)
Returns:
Share Improve this question asked 14 hours ago Pancake_stack_with_syrupPancake_stack_with_syrup 332 bronze badges 4 |2 Answers
Reset to default 0The following can give you your expression of taste. You can use your interactive prompt to see what each of the steps is doing. The cse
is there to collect that 2a+b
into a single term that doesn't expand when doing the expansion: r,e=cse(factor_terms(collect(expr,d)));expand(e[0]).subs(r)
The fact that expr.simplify()
does not return the exact result is due to the heuristics used by Sympy’s general simplify() function—it doesn’t guarantee a unique “simplest” form, only that the result is mathematically equivalent (as confirmed by correct_simpl.equals(expr))
.
If you require the result in that specific form, you can try using a more targeted function such as:
sp.factor_terms(expr)
expr.apart(d).collect(c)
. – kikon Commented 10 hours ago