[英]Assigning the outputs of fmin in scipy.optimize
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: 目前,我是通过以下Python脚本实现此目的的:
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. 因此,函数的最小值为〜0.71,并且对于〜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". 所以我收到一个错误“ ValueError:需要多个值来解压缩”。 Does anybody know how to prevent this error and assign those two outputs? 有人知道如何防止该错误并分配这两个输出吗?
fmin
has a full_output=True
parameter : fmin
具有full_output=True
参数 :
xopt, fopt, iter, funcalls, warnflag = fmin(T,0, full_output=True, disp=False)
print(xopt, fopt)
# (array([ 301.9498125]), 0.71004171552448025)
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. 因此,我没有为fmin指定多个输出,而是得到了参数,并再次使用该函数来获取最小值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.