Reputation: 509
In SymPy 1.3 I have some linear combinations like
N1*(-sqrt(15)/36 + 5/36) - 5*N2/18 + N3*(sqrt(15)/36 + 5/36)
How do I force the fractions to be (5-sqrt(15))/36
?
Upvotes: 1
Views: 2118
Reputation:
Apply together
, which can be called either as a function together(expr)
or a method expr.together()
. If it's applied to the entire expression, the result may be too much collecting:
N1, N2, N3 = symbols('N1 N2 N3')
expr = N1*(-sqrt(15)/36 + S(5)/36) - 5*N2/18 + N3*(sqrt(15)/36 + S(5)/36)
print(together(expr))
prints (N1*(-sqrt(15) + 5) - 10*N2 + N3*(sqrt(15) + 5))/36
.
Here is a version that selectively applies together
to the coefficient of each symbol.
for sym in expr.free_symbols:
expr = expr.xreplace({expr.coeff(sym): together(expr.coeff(sym))})
print(expr)
prints N1*(-sqrt(15) + 5)/36 - 5*N2/18 + N3*(sqrt(15) + 5)/36
.
Upvotes: 3
Reputation: 21643
This might be what you want.
Use sympy's Rational operator to force it to retain 5/36 in fractional form.
>>> from sympy import *
>>> N1 = 2
>>> N2 = 5
>>> N3 = 7
>>> (N1*(-sqrt(15)/36 + Rational(5, 36)) - 5*N2/18 + N3*(sqrt(15)/36 + Rational(5,36)))
-0.138888888888889 + 5*sqrt(15)/36
>>> import sympy
>>> sympy.__version__
'1.3'
Upvotes: 0