用numpy求解矩阵方程的错误

时间:2016-04-18 08:36:50

标签: python numpy sympy

我正在使用sympynumpy在Python中编写自己的Newton-Raphson算法。

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

CODE

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()

该函数的参数是:

fncList - 使用Sympy符号

的python函数列表

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

x0 - 初步猜测

错误

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

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

[-5.15598620617611, 5.13378681611922]

我跑的时候:

newtonRhapson([5*cos(a)+6*cos(a+b)-10, 5*sin(a)+6*sin(a+b)-4], [a,b], [0.7,0.7])

但在跑线上:

print numpy.linalg.solve(j,f).tolist()

我收到错误:

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

1 个答案:

答案 0 :(得分:6)

您的问题出在第二个for循环中。

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

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

要解决此问题,您只需为numpy.array添加dtype规范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'))