pythonscipyscipy-optimizeminimization

problem with minimize using SLSQP in python


I am getting a problem where it says float is not iterable when trying to minimize the following functions in python. I have checked, and the problem seems to lie with how I am using this minimization. Just to clarify, the values being passed through for a and b, will be between 0.0 and 1.0. Any ideas are greatly appreciated!

I have put some of the code here just to show:

def func1(x):
return (x-1)\*\*2

def func2(x):
return math.pow(x-0.5,2)

p1 = 1.0 - a
p2 = 1.0 - b

bound1 = (0.0,p1)
bound2 = (0.0,p2)

x0 = 0.5

result1 = minimize(func1, x0, method='SLSQP', bounds = bound1)#, options={'maxiter':3})
result2 = minimize(func2, x0, method='SLSQP', bounds = bound2)#, options={'maxiter':3})

newX = result1.x
newY = result2.x

Solution

  • The issue is that bounds expects a list of tuples (or a Bounds objects), and here you are just providing a single tuple.

    Since your cost functions only have a single argument to apply bounds to, you just need to change your current bounds to a list that contains a single tuple like so:

    # bound1 = (0.0,p1)
    bound1 = [(0.0,p1)]
    
    # bound2 = (0.0,p2)
    bound2 = [(0.0,p2)]
    

    Below is the working code:

    import math
    from scipy.optimize import minimize
    
    def func1(x):
        return (x-1) ** 2
    
    def func2(x):
        return math.pow(x-0.5,2)
    
    a, b = .2, .5
    p1 = 1.0 - a
    p2 = 1.0 - b
    
    bound1 = [(0.0,p1)]
    bound2 = [(0.0,p2)]
    
    x0 = 0.5
    
    result1 = minimize(func1, x0, method='SLSQP', bounds = bound1)#, options={'maxiter':3})
    result2 = minimize(func2, x0, method='SLSQP', bounds = bound2)#, options={'maxiter':3})
    
    newX = result1.x
    newY = result2.x
    
    print(newX, newY) # [0.8] [0.5]