我正在使用Scipy.Optimize.fmin查找函数的最大值。输出为numpy.ndarray的形式,其中包含有关该进程的其他信息。我只需要将x值作为浮点数返回即可。
def f(x):
"""returns the value of f(x) with the input value x"""
import math
f = math.exp(-x ** 2.0) / (1.0 + x ** 2.0) + \
2.0 * (math.cos(x) ** 2.0) / (1.0 + (x - 4.0) ** 2.0)
return f
def find_max_f():
"""returns the x for which f(x) takes the maximum value"""
import scipy.optimize as o
m = o.fmin(lambda x: -f(x), 0)
return m
这是返回的内容:
>>> find_max_f()
Optimization terminated successfully.
Current function value: -1.118012
Iterations: 12
Function evaluations: 24
array([ 0.0131875])
我只需要在括号内标记数组的最后一个数字
只需将结果绑定到某些东西,然后就可以索引第一个元素,就好像它是列表或元组一样:
>>> xopt = find_max_f()
Optimization terminated successfully.
Current function value: -1.118012
Iterations: 12
Function evaluations: 24
>>> xopt
array([ 0.0131875])
>>> xopt[0]
0.013187500000000005
>>> type(xopt[0])
<type 'numpy.float64'>
我建议阅读NumPy教程,特别是有关“索引,切片和迭代”的部分。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句