用numpy求解矩阵方程的错误

Gre*_*ory 9 python numpy sympy

我用我自己写牛顿迭代算法在Python sympynumpy.

代码如下,但您可以忽略它并跳过错误:

def newtonRhapson(fncList, varz, x0):

    jacob = []

    for fnc in fncList:
        vec = []
        for var in varz:
            res = fnc.diff(var)
            for i in range(len(varz)):
                res = res.subs(varz[i], x0[i])
            vec.append(res)
        jacob.append(numpy.array(vec, dtype='float64'))

    fx0=[]

    for fnc in fncList:
        res2 = fnc
        for i in range(len(varz)):
            res2 = res2.subs(varz[i], x0[i])
        fx0.append(res2)

    j = jacob
    f = fx0

    print j
    print ''
    print f

    print numpy.linalg.solve(j,f).tolist()
Run Code Online (Sandbox Code Playgroud)

该函数的参数是:

fncList- 使用Sympy符号的python函数列表

varz - 包含这些符号(变量)的列表

x0 - 初步猜测

错误

直到我们print jf它工作正常并打印以下内容:

[array([-9.13378682, -5.91269838]), array([ 4.84401379,  1.01980286])]

[-5.15598620617611, 5.13378681611922]
Run Code Online (Sandbox Code Playgroud)

当我跑:

newtonRhapson([5*cos(a)+6*cos(a+b)-10, 5*sin(a)+6*sin(a+b)-4], [a,b], [0.7,0.7])
Run Code Online (Sandbox Code Playgroud)

但在运行线路时:

print numpy.linalg.solve(j,f).tolist()
Run Code Online (Sandbox Code Playgroud)

我收到错误:

File "/Users/me/anaconda/lib/python2.7/site-  packages/numpy/linalg/linalg.py", line 384, in solve
r = gufunc(a, b, signature=signature, extobj=extobj)
TypeError: No loop matching the specified signature and casting was found for ufunc solve1
Run Code Online (Sandbox Code Playgroud)

mir*_*ulo 7

你的问题出在你的第二个for循环中.

for fnc in fncList:
    res2 = fnc
    for i in range(len(varz)):
        res2 = res2.subs(varz[i], x0[i])
    fx0.append(res2)
Run Code Online (Sandbox Code Playgroud)

当您追加时fx0,您需要确保附加相同的类型(float64),以便NumPy可以使用LAPACK计算系统的行列式(有关详细信息,请参阅此答案).您当前正在追加<class 'sympy.core.numbers.Float'>- 您的错误消息告诉您使用的类型签名不正确.

要解决此问题,你可以简单地追加numpy.arraydtype规范float64如同上面一样

for fnc in fncList:
    res2 = fnc
    for i in range(len(varz)):
        res2 = res2.subs(varz[i], x0[i])
    fx0.append(numpy.array(res2, dtype='float'))
Run Code Online (Sandbox Code Playgroud)

  • 对于googlers的评论 - 这是你会得到许多numpy函数的错误,你有错误的数据类型(对我来说,它是一个np.linalg.pinv(x),其中x是错误的对象dtype) (4认同)