python 中的多变量牛顿法(方程组)
Newton method in python for multivariables (system of equations)
我的代码 运行 第一次迭代没问题,但之后它输出以下错误:
ValueError: matrix must be 2-dimensional
据我所知(在 python 中并不多),我的代码是正确的。但我不知道,为什么它不是 运行 对于所有给定的迭代都是正确的。谁能帮我解决这个问题。
from __future__ import division
import numpy as np
import math
import matplotlib.pylab as plt
import sympy as sp
from numpy.linalg import inv
#initial guesses
x = -2
y = -2.5
i1 = 0
while i1<5:
F= np.matrix([[(x**2)+(x*y**3)-9],[(3*y*x**2)-(y**3)-4]])
theta = np.sum(F)
J = np.matrix([[(2*x)+y**3, 3*x*y**2],[6*x*y, (3*x**2)-(3*y**2)]])
Jinv = inv(J)
xn = np.array([[x],[y]])
xn_1 = xn - (Jinv*F)
x = xn_1[0]
y = xn_1[1]
#~ print theta
print xn
i1 = i1+1
xn_1
是一个 numpy 矩阵,所以它的元素是用 item()
方法访问的,不像数组。 (有 []
s)
所以改变一下
x = xn_1[0]
y = xn_1[1]
到
x = xn_1.item(0)
y = xn_1.item(1)
我相信 xn_1
是一个二维矩阵。尝试打印出来,您会看到 [[something], [something]]
因此要得到x和y,需要使用多维索引。这是我做的
x = xn_1[0,0]
y = xn_1[1,0]
之所以可行,是因为在二维矩阵 xn_1
中有两个单元素数组。因此,我们需要进一步索引 0 以获得该单个元素。
编辑:澄清一下,xn_1[1,0]
表示索引 1,然后取该子数组并在其上索引 0。 And although according to Scipy it may seem that it should be functionally equivalent to xn_1[1][0]
, that only applies to the general np.array
type and not the np.matrix
type. 。
所以你应该使用xn_1[1,0]
方式获取你想要的元素。
我的代码 运行 第一次迭代没问题,但之后它输出以下错误:
ValueError: matrix must be 2-dimensional
据我所知(在 python 中并不多),我的代码是正确的。但我不知道,为什么它不是 运行 对于所有给定的迭代都是正确的。谁能帮我解决这个问题。
from __future__ import division
import numpy as np
import math
import matplotlib.pylab as plt
import sympy as sp
from numpy.linalg import inv
#initial guesses
x = -2
y = -2.5
i1 = 0
while i1<5:
F= np.matrix([[(x**2)+(x*y**3)-9],[(3*y*x**2)-(y**3)-4]])
theta = np.sum(F)
J = np.matrix([[(2*x)+y**3, 3*x*y**2],[6*x*y, (3*x**2)-(3*y**2)]])
Jinv = inv(J)
xn = np.array([[x],[y]])
xn_1 = xn - (Jinv*F)
x = xn_1[0]
y = xn_1[1]
#~ print theta
print xn
i1 = i1+1
xn_1
是一个 numpy 矩阵,所以它的元素是用 item()
方法访问的,不像数组。 (有 []
s)
所以改变一下
x = xn_1[0]
y = xn_1[1]
到
x = xn_1.item(0)
y = xn_1.item(1)
我相信 xn_1
是一个二维矩阵。尝试打印出来,您会看到 [[something], [something]]
因此要得到x和y,需要使用多维索引。这是我做的
x = xn_1[0,0]
y = xn_1[1,0]
之所以可行,是因为在二维矩阵 xn_1
中有两个单元素数组。因此,我们需要进一步索引 0 以获得该单个元素。
编辑:澄清一下,xn_1[1,0]
表示索引 1,然后取该子数组并在其上索引 0。 And although according to Scipy it may seem that it should be functionally equivalent to xn_1[1][0]
, that only applies to the general np.array
type and not the np.matrix
type.
所以你应该使用xn_1[1,0]
方式获取你想要的元素。