Klifton Black
Klifton Black

Reputation: 11

How to make sympi arrange formula so that the highest order coefficient in the numerator is one

I am using sympy and python to solve some equations. I am trying to arrange an equation so that the coefficient in terms of the highest degree is +1. For example the following code produces the output

Km, Kb, L, s, R, J, b = sym.symbols("Km, Kb, L, s, R, J, b")
G1 = Km / (L * s + R)
G2 = 1 / (J * s + b)
Msys = (G1 * G2) / (1 + G1 * G2 * Kb)
Msys = sym.expand(Msys)
Msys = sym.simplify(Msys)
Msys = sym.collect(Msys, s)

print(Msys)

#outputs Km/(J*L*s**2 + Kb*Km + R*b + s*(J*R + L*b))

I need to get rid of coefficients in front of s**2 (ie set to 1). This would normally be done by dividing both the top and bottom by J*L. I found a sympi function called monic that is supposed to do this but it only works on the numerator.

What is the best solution to this problem?

Thanks is advance

Upvotes: 0

Views: 139

Answers (1)

Klifton Black
Klifton Black

Reputation: 11

This is not an ideal solution because it gets the formula in the form that I need it. Basically I split the formula up into top and bottom, then I multiply by 1 / (J * L) the coefficients in front of the highest degree variable.

Km, Kb, L, R, J, b, Gc, Ain, Amp, Hoi, s = sym.symbols("Km, Kb, L, R, J, b, Gc, Ain, Amp, Hoi, s")
G1 = 1/ (L * s + R)
print(G1)
G2 = 1 / (J * s + b)
print(G2)

Msys = (Km * G1 * G2) / (1 + Km * G1 * G2 * Kb)
Msys = sym.expand(Msys)
Msys = sym.simplify(Msys)
Msys = sym.collect(Msys, s)
g3 = Msys * ((1/(J*L))/(1/(J*L)))
print(g3)
top, bot = Msys.as_numer_denom()
top = top * (1/(J*L))
print(top)
bot = bot * (1/(J*L))
bot = sym.expand(bot)
bot = sym.collect(bot, s)

print(bot)

Msys = top * 1/bot

While this solution worked it is not ideal, because of its complexity. I could probably further develop it and make it into a function I can reuse, but there must be an easier way

Upvotes: 1

Related Questions