将有限 Laurent 级数(Laurent 多项式)表示为字典
Express a finite Laurent series (a Laurent polynomial) as a dictionary
假设您有一个多元多项式表达式,并且您希望通过每个单项式的次数和系数将其表征为字典。
示例:
p=Poly(3*x1**2 - x1*x2 + 5*x2 +7)
你想要:
dic={"(2,0)":3 , "(1,1)":-1 , "(0,1)": 5 , "(0,0)": 7}
p.as_dict()
很好地解决了问题。
现在,您遇到了同样的问题,但现在多元多项式表达式允许负指数(有限洛朗级数)。
所以如果你有:
p=Poly(3*x1**-2 - x1*x2 + 5*x2)
p.as_dict()
将打印:
{(0, 0, 2): 3, (0, 1, 0): 5, (1, 1, 0): -1}
但是,我想要这个:
{(-2, 0): 3, (0, 1): 5, (1, 1): -1}
我怎样才能优雅地实现这个目标?
似乎最简单的方法是将表达式乘以每个变量的足够大的幂,使其成为实际的多项式。将其转换为字典,然后减去我们乘以的幂。设置:
x1, x2 = symbols('x1 x2')
syms = (x1, x2) # specify the desired order of symbols: do not rely on default order being what you want
expr = 3*x1**(-2) - x1*x2 + 5*x2 # just an expression so far, not a polynomial
主要代码:
d = max(Poly(expr).degree_list())
prelim = Poly(expr*prod([x**d for x in syms]), syms).as_dict()
final = {tuple(deg - d for deg in key): prelim[key] for key in prelim}
解释:Poly(expr)
创建变量 x1、x2、1/x1 的多项式。通过让
d
是每个变量中的最大度数,保证x1**d * x2**d * expr
不会有负次幂。此乘积在 (x1, x2)
中做多项式并转换为 "preliminary" 字典:{(0, 2): 3, (2, 3): 5, (3, 3): -1}
。然后调整字典,处处减去d
。最终结果:
{(-2, 0): 3, (0, 1): 5, (1, 1): -1}
假设您有一个多元多项式表达式,并且您希望通过每个单项式的次数和系数将其表征为字典。
示例:
p=Poly(3*x1**2 - x1*x2 + 5*x2 +7)
你想要:
dic={"(2,0)":3 , "(1,1)":-1 , "(0,1)": 5 , "(0,0)": 7}
p.as_dict()
很好地解决了问题。
现在,您遇到了同样的问题,但现在多元多项式表达式允许负指数(有限洛朗级数)。
所以如果你有:
p=Poly(3*x1**-2 - x1*x2 + 5*x2)
p.as_dict()
将打印:
{(0, 0, 2): 3, (0, 1, 0): 5, (1, 1, 0): -1}
但是,我想要这个:
{(-2, 0): 3, (0, 1): 5, (1, 1): -1}
我怎样才能优雅地实现这个目标?
似乎最简单的方法是将表达式乘以每个变量的足够大的幂,使其成为实际的多项式。将其转换为字典,然后减去我们乘以的幂。设置:
x1, x2 = symbols('x1 x2')
syms = (x1, x2) # specify the desired order of symbols: do not rely on default order being what you want
expr = 3*x1**(-2) - x1*x2 + 5*x2 # just an expression so far, not a polynomial
主要代码:
d = max(Poly(expr).degree_list())
prelim = Poly(expr*prod([x**d for x in syms]), syms).as_dict()
final = {tuple(deg - d for deg in key): prelim[key] for key in prelim}
解释:Poly(expr)
创建变量 x1、x2、1/x1 的多项式。通过让
d
是每个变量中的最大度数,保证x1**d * x2**d * expr
不会有负次幂。此乘积在 (x1, x2)
中做多项式并转换为 "preliminary" 字典:{(0, 2): 3, (2, 3): 5, (3, 3): -1}
。然后调整字典,处处减去d
。最终结果:
{(-2, 0): 3, (0, 1): 5, (1, 1): -1}