How to find Coefficient of more than one variable of desired power in Python

billy :

if I had an equation with more than one variable, lets say x**2+x*y+y**2, I could find Coefficients with CoefficientList from Mathematica. It would print the desired matrix as 3x3.

In Python, I found sympy.coeff(x, n) but I can not return the coefficient for more than one variable.

Is there a way you know?

JohanC :

Here is a way to find each of the coefficients of the quadratic form and represent them as a matrix:

import sympy as sy
from sympy.abc import x, y

def quadratic_form_matrix(expr, x, y):
    a00, axx, ayy, ax, ay, axy = sy.symbols('a00 axx ayy ax ay axy')
    quad_coeffs = sy.solve([sy.Eq(expr.subs({x: 0, y: 0}), a00),
                            sy.Eq(expr.diff(x).subs({x: 0, y: 0}), 2 * ax),
                            sy.Eq(expr.diff(x, 2).subs({y: 0}), 2 * axx),
                            sy.Eq(expr.diff(y).subs({x: 0, y: 0}), 2 * ay),
                            sy.Eq(expr.diff(y, 2).subs({x: 0}), 2 * ayy),
                            sy.Eq(expr.diff(x).diff(y), 2 * axy)],
                           (a00, axx, ayy, ax, ay, axy))
    return sy.Matrix([[axx, axy, ax], [axy, ayy, ay], [ax, ay, a00]]).subs(quad_coeffs)

expr = x**2 + 2*x*y + 3*y**2 + 7
M = quadratic_form_matrix(expr, x, y)
print(M)

XY1 = sy.Matrix([x, y, 1])
quadatric_form = (XY1.T * M * XY1)[0]
print(quadatric_form.expand())

PS: Applying a conversion to a multivariate polygon as suggested @Marcus' reference, and then converting to a matrix would result in following code. Note that to get the constant term, 1 can be passed to coeff_monomial(1). The non-diagonal elements of the symmetric matrix for the quadratic form need to be half of the corresponding coefficients.

import sympy as sy
from sympy.abc import x, y

def quadratic_form_matrix_using_poly(expr, x, y):
    p = sy.poly(expr)
    axx = p.coeff_monomial(x * x)
    ayy = p.coeff_monomial(y * y)
    a00 = p.coeff_monomial(1)
    ax = p.coeff_monomial(x) / 2
    ay = p.coeff_monomial(y) / 2
    axy = p.coeff_monomial(x * y) / 2
    return sy.Matrix([[axx, axy, ax], [axy, ayy, ay], [ax, ay, a00]])

expr = x**2 + 2*x*y + 3*y**2 + 7 + 11*x + 23*y

M = quadratic_form_matrix(expr, x, y)
print(M)

XY1 = sy.Matrix([x, y, 1])
quadatric_form = (XY1.T * M * XY1)[0]
print(quadatric_form.expand())

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=23801&siteId=1