import sympy
import numpy
from sympy import ordered, Matrix
x1,x2=sympy.symbols('x1 x2')
f=x1**2-x1*x2-4*x1 x2**2-x2
X0=numpy.array([[1],[1]])
v = list(ordered(f.free_symbols))
gradient = lambda f, v: Matrix([f]).jacobian(v)
gradf=sympy.transpose(gradient(f, v))
gradfx0=(gradf.subs([(x1, X0[0]), (x2, X0[1])]))
print(gradfx0)
I want to calculate the gradient of two variable function in a point in python. I define the function and I find the gradient vector of function (grad). Now when I try to substituting X0 to grad, the result is
Matrix([[2*x1 - x2 - 4], [-x1 2*x2 - 1]]).
I want the result should be
Matrix([[-3], [0]]).
How to substituting a point to sympy array?
CodePudding user response:
Using .subs and derive_by_array:
from sympy import symbols
from sympy.tensor.array import derive_by_array
x1, x2 = symbols('x1 x2')
f = x1 ** 2 - x1 * x2 x2 ** 2 - 4 * x1 - x2
grad = derive_by_array(f, (x1, x2))
# = [2*x1 - x2 - 4, -x1 2*x2 - 1]
gradx0 = grad.subs({x1: 1, x2: 1})
# = [-3, 0]
If you want to call your point x0 first, then use variable x0:
x0 = (1, 1)
gradx0 = grad.subs(zip((x1,x2), x0))
# = [-3, 0]
