3

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

1
  • What is the return type of fmin()? If it's an iterable you might be able to grab it using the index. Commented Jan 9, 2014 at 20:42

1 Answer 1

3

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".

Sign up to request clarification or add additional context in comments.

2 Comments

You might also want to mention unpacking. E.g. xopt, = find_max_f() (or m, = o.fmin(...) inside find_max_f.) It winds up confusing a lot of newcomers, but it's a common idiom, so it might be good for the OP to see it as well.
I think you just did. :^) Can't quite explain why I don't use that pattern, but I never use it in my own code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.