Printing a polynomial so that the powers of x or s are in ascending or descending order

旧巷老猫 提交于 2021-02-17 04:41:26

问题


I can't find a method or function that will order the powers of the polynomial terms in either ascending or descending order. I am using sympy to calculate some transfer functions using Laplace transforms.

I have found only collect() helps combine powers of s but it can't print the powers of s in ascending or descending order. I see print outs like this

CLTF(s)=(K*Kd*ω**2*s + K*Kp*ω**2)/(K*Kp*ω**2 + 2*ζ*ω*s**2 + s**3 + s*(K*Kd*ω**2 + ω**2))

The powers of s are not in the right order in the denominator

from math import pi
from sympy import symbols, init_printing, ratsimp, fraction, pprint, collect
from sympy.solvers import solve
import matplotlib.pyplot as plt
init_printing()
s, c0, c1, c2, c3, c4 = symbols('s, c0, c1, c2, c3, c4')
Ki, Kp, Kd, K2 = symbols('Ki, Kp, Kd, K2')
K, nf, df = symbols('K, nf, df')
cltf, Ga, Gc, num, den = symbols('cltf, Ga, Gc, num, den')

Gc = Kp+Kd*s                                 # controller transfer function
Ga = 5/(s*(s**2+4*s+5))                 # open loop transfer function
Ga = 5/(s*(s**2+2*s+5))                 # open loop transfer function
Ga = K*nf**2/(s*(s**2+2*df*nf*s+nf**2))
# calculate the symbolic equation for  the closed loop transfer function
cltf = collect(ratsimp((Gc*Ga)/(1+Gc*Ga)),s)
print("\n\nClosed Loop Transfer Function = ")
pprint(cltf)
(num, den) = fraction(cltf)             # separate into numerator and denominator
print("\n\nCharacteristic Equation = ")
pprint(collect(den,s))
zeros = solve(num,s)                    # find the symbolic zeros
roots = solve(den,s)                    # find the symbolic roots
num_str=str(num)
num_str0 = num_str.replace("nf",u"\u03C9")
den_str=str(collect(den,s))
den_str0 = den_str.replace("nf",u"\u03C9")
den_str1 = den_str0.replace("df",u"\u03B6")
print("\n\nCLTF(s)=({})/({})".format(num_str0,den_str1))

There are no error messages. I simply do not get the print out I want. The powers of s are not in any order. Also there is no horner function that would print a third order polynomial like this

((d*x+c)*x+b)*x+a instead of a+b*x+c*x**2+d*x**3

来源:https://stackoverflow.com/questions/56652669/printing-a-polynomial-so-that-the-powers-of-x-or-s-are-in-ascending-or-descendin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!