如何从numpy.ndarray中提取值

bsxbgnwa  于 2023-01-17  发布在  其他
关注(0)|答案(1)|浏览(253)

我正在使用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])

我只需要括号中的最后一个数字

iq3niunx

iq3niunx1#

只需将结果绑定到某个对象,然后就可以将第一个元素当作列表或元组来索引:

>>> 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 Tutorial,特别是关于“索引、切片和迭代”的部分。

相关问题