本文介绍了ValueError:函数返回的数组在调用 scipy.fsolve() 之间改变了大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 scipy.optimize.fsolve() 来求解使函数等于 0 的 x,但一直出现上述错误.我的代码是:

I am trying to use scipy.optimize.fsolve() to solve for x that makes the function equal to zero, but keep getting the error above. My code is:

import scipy.optimize as optimize
from scipy.stats import genextreme as gev

gevcombined = [(-0.139, 3.035, 0.871),(-0.0863, 3.103, 0.818),(-0.198, 3.13, 0.982)]
ratio = [0.225, 0.139, 0.294]
P = [0.5,0.8,0.9,0.96,0.98,0.99]
def mixedpop(x):
    for j in range(len(ratio)):
        F = (ratio[j]*gev.cdf(x,gevcombined[j][0],gevcombined[j][1],gevcombined[j][2]))+((1-ratio[j]*gev.cdf(x,gevcombined[j][0],gevcombined[j][1],gevcombined[j][2]))-P
    return F

initial = 10
Rm = optimize.fsolve(mixedpop,initial)

我不断收到错误消息:

ValueError:the array returned by a function changed size between calls

这个错误是什么意思?预期输出将是每个 P 值的值.因此,对于每个比率,来自 Rm 的 x 值将等于 [3.5, 4, 5.4, 6.3, 7.2, 8.1] 之类的东西

What does this error mean? The expected output would be a value for each value of P. So the values of x from Rm would equal something like [3.5, 4, 5.4, 6.3, 7.2, 8.1] for each ratio

推荐答案

好的,我想出了如何让 fsolve 为一系列解决方案工作.

Okay I figured out how to get fsolve to work for an array of solutions.

如果我把整个事情写成这样就行了:

It works if I write the whole thing like this:

Rm = []
initial = [10,10,10,10,10,10]
for j in range(len(ratio)):
    f = lambda x : (ratio[j]*gev.cdf(x,gevcombined[j][0],gevcombined[j][1],gevcombined[j][2]))+((1-ratio[j]*gev.cdf(x,gevcombined[j][0],gevcombined[j][1],gevcombined[j][2]))-P
    Rm.append(list(optimize.fsolve(f,initial)))

我的输出是:

[[3.37, 4.37, 5.13, 6.43, 7.91, 9.88],[3.41, 4.42, 5.09, 6.13, 7.07, 8.18],[3.49, 4.87, 5.95, 7.51, 8.80, 10.19]]

这篇关于ValueError:函数返回的数组在调用 scipy.fsolve() 之间改变了大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 08:30