首页 > 解决方案 > 打印多项式,使 x 或 s 的幂按升序或降序排列

问题描述

我找不到可以按升序或降序对多项式项的幂进行排序的方法或函数。我正在使用 sympy 使用拉普拉斯变换计算一些传递函数。

我发现只有 collect() 有助于组合 s 的幂,但它不能按升序或降序打印 s 的幂。我看到这样的打印输出

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

s 的幂在分母中的顺序不正确

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))

没有错误消息。我根本没有得到我想要的打印出来。s 的幂没有任何顺序。也没有 horner 函数可以打印这样的三阶多项式

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

标签: pythonsympy

解决方案


推荐阅读