1

posted at

updated at

[Python]sympyを使って多項式から任意の着目する変数の係数を求める方法

``````import sympy as sp

sp.var('x1, x2, x3')		# 着目する変数
sp.var('c1, c2, c3, c4, c5')	# 係数
expr = c1*x1 + c2*x2 + c3*x3 + c4*x1*x2 + c5	# 式を定義

expr_poly = sp.poly(expr, x1, x2, x3)	# x1,x2,x3に着目した多項式オブジェクトを作成
x1_coef = expr_poly.nth(1, 0, 0)	# x1の係数
x2_coef = expr_poly.nth(0, 1, 0)	# x2の係数
x3_coef = expr_poly.nth(0, 0, 1)	# x3の係数
x1_x2_coef = expr_poly.nth(1, 1, 0)	# x1*x2の係数
constant = expr_poly.nth(0, 0, 0)	# 定数

print(x1_coef, x2_coef, x3_coef, x1_x2_coef, constant)
# 実行結果 -> c1 c2 c3 c4 c5
``````

(補足)polyやnthの引数は可変長引数になっているので引数の展開を使うとリストのまま扱えて便利

``````variableList = [x1, x2, x3]
expr_poly = sp.poly(expr, *variableList)
x1_coef = expr_poly.nth(*[1, 0, 0])
x2_coef = expr_poly.nth(*[0, 1, 0])
x3_coef = expr_poly.nth(*[0, 0, 1])
x1_x2_coef = expr_poly.nth(*[1, 1, 0])
constant = expr_poly.nth(*[0, 0, 0])
``````

参考資料

Sympy公式ドキュメント

Register as a new user and use Qiita more conveniently

1. You get articles that match your needs
2. You can efficiently read back useful information
What you can do with signing up
1