问题
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)
I keep getting the error:
ValueError:the array returned by a function changed size between calls
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
回答1:
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)))
And my output is:
[[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]]
回答2:
the error occures because the shape of initial does not match your variables.
initial = np.ones(len(x))
However I cannot make my head around what your function is doing. it does the trick for me.
来源:https://stackoverflow.com/questions/54715389/valueerror-the-array-returned-by-a-function-changed-size-between-calls-scipy-fs