I have a function of a single variable which I'd like to find the minimum value of, as well as the value of the variable where the minimum is attained. Currently I achieve this through the following Python script:
import numpy as np
from scipy.optimize import fmin
import math
x1=0.
y1=800.
x2=1100.
y2=-800.
v1=2000.
v2=4000.
def T(xi):
time=sqrt((x1-xi)**2+y1**2)/v1+sqrt((x2-xi)**2+y2**2)/v2
return time
fmin(T,0)
Running this script produces the following echo:
import numpy as np
from scipy.optimize import fmin
import math
x1=0.
y1=800.
x2=1100.
y2=-800.
v1=2000.
v2=4000.
def T(xi):
time=sqrt((x1-xi)**2+y1**2)/v1+sqrt((x2-xi)**2+y2**2)/v2
return time
fmin(T,0)
Optimization terminated successfully.
Current function value: 0.710042
Iterations: 41
Function evaluations: 82
Out[24]: array([ 301.9498125])
So the minimum value of the function is ~0.71 and is attained for a value of the argument of ~302. I would, however, like to assign these values as follows:
(Tmin,xmin)=fmin(T,0)
Optimization terminated successfully.
Current function value: 0.710042
Iterations: 41
Function evaluations: 82
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
C:\Users\Kurt.Peek\<ipython-input-25-aec613726d59> in <module>()
----> 1 (Tmin,xmin)=fmin(T,0)
ValueError: need more than 1 value to unpack
So I get an error "ValueError: need more than 1 value to unpack". Does anybody know how to prevent this error and assign those two outputs?
fmin
has a full_output=True
parameter:
xopt, fopt, iter, funcalls, warnflag = fmin(T,0, full_output=True, disp=False)
print(xopt, fopt)
# (array([ 301.9498125]), 0.71004171552448025)