how to extract value from a numpy.ndarray

Question:

I’m using Scipy.Optimize.fmin to find the maximum of a function. The output is in the form of a numpy.ndarray with additional information on the process. I need just the x value returned as a float.

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

This is what it returns:

>>> find_max_f()
Optimization terminated successfully.
     Current function value: -1.118012
     Iterations: 12
     Function evaluations: 24
array([ 0.0131875])

I just need the final number inside the brackets labeled array

Asked By: user3179258

||

Answers:

Simply bind the result to something and then you can index the first element as if it were a list or tuple:

>>> 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'>

I recommend reading the NumPy Tutorial, in particular the section on "Indexing, Slicing and Iterating".

Answered By: DSM
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.