使用numpy求解矩阵方程式时出错 [英] Error solving Matrix equation with numpy

查看:128
本文介绍了使用numpy求解矩阵方程式时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing my own Newton-Raphson algorithm in Python using sympy and numpy.

下面是代码,但您可以忽略此代码并跳至错误:

The code is below but you can ignore this and skip on to the error:

代码

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函数列表

fncList - a python list of functions using Sympy symbols

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

varz - a list containing those symbols (variables)

x0-初步猜测

错误

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

Up until the point where we print j and f it works fine and prints the following:

[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

推荐答案

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

Your issue is in your second for loop.

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计算系统的行列式(请参见

When you append to fx0, you need to ensure that you are appending the same type (float64) such that NumPy can compute the determinant of your system with LAPACK (see this answer for more info). You are currently appending <class 'sympy.core.numbers.Float'> - your errror message is telling you that you have an incorrect type signature for usage.

要纠正此问题,您只需像上面所做的那样,为float64附加numpy.arrayfloat64规范即可.

To correct this issue, you can simply append numpy.array with a dtype specification for float64 as you did above

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

这篇关于使用numpy求解矩阵方程式时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆