Question

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?

Was it helpful?

Solution

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)

OTHER TIPS

The following achieves the same thing: at the end of the script I added

xmin=fmin(T,0)
Tmin=T(xmin)

This yields the desired outputs:

xmin
Out[30]: array([ 301.9498125])

T(xmin)
Out[31]: array([ 0.71004172])

So instead of specifying several outputs for fmin, I got just the argument and used the function again to obtain the minimum value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top