【问题标题】:Error solving Matrix equation with numpy用 numpy 求解矩阵方程时出错
【发布时间】:2016-04-18 08:36:49
【问题描述】:

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

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

代码

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 j 和 f 它工作正常并打印以下内容:

[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

【问题讨论】:

    标签: python numpy sympy


    【解决方案1】:

    您的问题在于您的第二个 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 计算系统的行列式(请参阅 this answer 了解更多信息)。您当前正在附加 <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'))
    

    【讨论】:

    • 对 googlers 的评论 - 对于许多 numpy 函数,您会遇到相同的错误,其中您有错误的数据类型(对我来说,它是 np.linalg.pinv(x),其中 x 错误地是一个对象 dtype)
    猜你喜欢
    • 2021-04-08
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    相关资源
    最近更新 更多