7

Trying to solve a simple non linear minimization problem with one variable.

from scipy.optimize import minimize
import math

alpha = 0.05
waiting = 50
mean_period = 50
neighborhood_size = 5

def my_func(w):
    return -(2/(w+1) + alpha*math.floor(waiting/mean_period))*(1-(2/(w+1) + alpha*math.floor(waiting/mean_period)))**(neighborhood_size-1)

print minimize(my_func, mean_period, bounds=(2,200))

which gives me

ValueError: length of x0 != length of bounds

Do I input it wrong? How should I format it?

And if I remove the bounds, I get:

status: 2
  success: False
     njev: 19
     nfev: 69
 hess_inv: array([[1]])
      fun: array([-0.04072531])
        x: array([50])
  message: 'Desired error not necessarily achieved due to precision loss.'
      jac: array([-1386838.30676792])

The function looks like that and therefore I need the bounds to limit the solution in the local maximum that I am interested in.

George
  • 774
  • 2
  • 9
  • 18
  • 6
    could you try bounds=((2,200),)? – ambi Aug 12 '14 at 17:05
  • 1
    @ambi , actually that solved it. I guess I did a typo in the first attempt. A quick counter question: coming from a C background it is easy to determine the type of the argument from the function signature. In that scenario, how could a new user know that it takes a tuple without actually looking at the source (https://github.com/scipy/scipy/blob/v0.14.0/scipy/optimize/_minimize.py#L37)? – George Aug 12 '14 at 23:47

1 Answers1

12

It should be:

print minimize(my_func, mean_period, bounds=((2,200),))

  status: 0
 success: True
    nfev: 57
     fun: array([-0.08191999])
       x: array([ 12.34003932])
 message: 'CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL'
     jac: array([  2.17187379e-06])
     nit: 4

For each parameter you have to provide a bound, therefore here we need to pass a tuple, which contains only one tuple (2,200), to minimize().

CT Zhu
  • 52,648
  • 17
  • 120
  • 133
  • 1
    As I mentioned in the comment above, I come from a C background where it is easy to determine the type of the argument from the function signature. In that scenario, how could a new user know that it takes a tuple without actually looking at the source (https://github.com/scipy/scipy/blob/v0.14.0/scipy/optimize/_minimize.py#L37)? – George Aug 13 '14 at 19:31
  • @George Unfortunately one of the issues in Python is that it is difficult to see what types a function takes in. It's usually up to the documentation to make this clear - in the documentation for minimize() it says that bounds is a "sequence" - the reason it does not specify a tuple is because this would actually work with any iterable, it could be a list for example. – mxbi Apr 12 '17 at 00:37