我想是关于数组维数的一些问题

2024-09-27 09:29:49 发布

您现在位置:Python中文网/ 问答频道 /正文

通过这段代码,我想用牛顿法从二维函数中找到一个最小值:

from numpy import array

from numpy.linalg import solve, norm

def newton2d(f, df, x, tol=1e-12, maxit=50):

    x = atleast_2d(x)

    for i in range(maxit):

        s = solve(df(x), f(x))
        x -=s
        if norm(s)<tol: print(x); print(i); break

f = lambda x: array([x[0]**2-x[1]**4, x[0]-x[1]**3])

df = lambda x: array([[2*x[0], -4*x[1]**3], [1, -3*x[1]**2]])


x = array([0.7, 0.7])

newton2d(f,df,x)

我认为这个代码应该可以工作,但我得到一个错误,如下所示:

IndexError: index 1 is out of bounds for axis 0 with size 1

谢谢你的帮助


Tags: lambda函数代码fromimportnumpynormdf

热门问题