sympy.subs 无法将点替换为数组
sympy.subs cannot substituting a point to array
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)
我想计算python
中某点的二变函数的梯度。我定义函数并找到函数的梯度向量 (grad
)。现在,当我尝试将 X0
替换为 grad
时,结果是
Matrix([[2*x1 - x2 - 4], [-x1 + 2*x2 - 1]])
.
我想要的结果应该是
Matrix([[-3], [0]]).
如何将点替换为 sympy 数组?
使用.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]
如果你想先调用你的点x0
,然后使用变量x0
:
x0 = (1, 1)
gradx0 = grad.subs(zip((x1,x2), x0))
# = [-3, 0]
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)
我想计算python
中某点的二变函数的梯度。我定义函数并找到函数的梯度向量 (grad
)。现在,当我尝试将 X0
替换为 grad
时,结果是
Matrix([[2*x1 - x2 - 4], [-x1 + 2*x2 - 1]])
.
我想要的结果应该是
Matrix([[-3], [0]]).
如何将点替换为 sympy 数组?
使用.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]
如果你想先调用你的点x0
,然后使用变量x0
:
x0 = (1, 1)
gradx0 = grad.subs(zip((x1,x2), x0))
# = [-3, 0]