【问题标题】:fsolve - mismatch between input and outputfsolve - 输入和输出不匹配
【发布时间】:2014-03-17 08:06:53
【问题描述】:

我正在尝试求解具有三个未知数的超定方程组。通过 for 循环调用方程组,我可以在 MATLAB 中使用 fsolve 和 lsqnonlin 获得解决方案。

但是在使用 scipy 的 python 中,我收到以下错误消息:

fsolve: there is a mismatch between the input and output shape of the 'func' argument 'fnz'

代码如下:

from xlrd import open_workbook
import numpy as np
from scipy import optimize
g = [0.5,1,1.5]
wb = open_workbook('EThetaValuesA.xlsx')
sheet=wb.sheet_by_index(0)
y=sheet.col_values(0,1)
t1=sheet.col_values(1,1)
t2=sheet.col_values(2,1)
t3=sheet.col_values(3,1)

def fnz(g):
    i=0
    sol=[0 for i in range(len(t1))]
    x1 = g[0]
    x2 = g[1]
    x3 = g[2]
    print len(t1)
    for i in range(len(t1)):
        # various set of t1,t2 and t3 gives the various eqns
        print i
        sol[i]=x1+t1[i]/(x2*t2[i]+x3*t3[i])-y[i]    
    return sol

Anz = optimize.fsolve(fnz,g)

print Anz

谁能指出我错在哪里?提前谢谢你。

【问题讨论】:

    标签: python excel numpy scipy


    【解决方案1】:

    异常表示fnz()函数调用的结果与输入g的维度不同,输入g是3个元素的列表,或者可以看作是array形状(3,) .

    为了说明问题,如果我们定义:

    def fnz(g):
        return [2,3,5]
    Anz = optimize.fsolve(fnz,g)
    

    不会有这样的例外。但这会:

    def fnz(g):
        return [2,3,4,5]
    Anz = optimize.fsolve(fnz,g)
    

    fnz() 的结果应该与t1 具有相同的长度,我确信它超过 3 个元素。

    【讨论】:

    • 这里 g 包含 x1、x2 和 x3 应该采用的初始猜测值。我这样给出是因为 scipy.optimize.fsolve(func, x0, args=(), fprime=None, full_output=0, col_deriv=0, xtol=1.49012e-08, maxfev=0, band=None, epsfcn= 0.0,因子=100,诊断=无,警告=真)
    • 我将函数输出更改为长度(t1)。但它对 x1、x2 和 x3 给出了一些奇怪的结果。我在 MATLAB 中使用与上面类似的代码得到的结果给出了准确的答案。是否需要在代码中进行更改(使 python 代码在功能级别上类似于 MATLAB 代码)。
    猜你喜欢
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多