Join the social network of Tech Nerds, increase skill rank, get work, manage projects...

• # How to Solve Optimization in scpy.optimize.minimize Problem? @NeoRaca • 0
• 0
• 0
• 0
• 0
• 0
• 0
• 167

I have a problem with optimizing of a function that contains loops. I start with paricular `lista=[0.002,0.006,0.003,0.02,0.008,0.006,0.05]` of floats and the intervals `(0,k*0.0025),(0.005,k*0.005),(0.005,k*0.0125), where upper border depends. So, depending on which of the interval the float of list belong to, I assign to the function one of values k*0.005,k*0.01,k*0.025 and k*0.05 that also depend on k.

I want to minimize `k` such that the sum (new scalar function) of values of `assign(k)` or `sum(assign(k))` is equal to 0.32.

I used `scipy.optimize` procedure to do that. My constraint is `constraint=sum(assign(k))-0.2` and objective function iz `fun(k)=k`. So, I minimized `k` to satisfy the constraint.

``````import scipy
from scipy.optimize import minimize

lista=[0.002,0.006,0.003,0.02,0.008,0.006,0.05]

def assign(k):
return list(map(lambda x:(k*0.005 if x in np.arange(0,k*0.0025,0.001)
else k*0.01 if x in np.arange(0.0025,k*0.005,0.001) else k*0.025 if x in
np.arange(0.005,k*0.0125,0.001) else k*0.05), lista))

def constraint(k):
return sum(assign(k))-0.32

def fun(k):
return k

k0=0
bnds=[(0,10)]
cons={'type':'eq','fun':constraint}
res=minimize(fun,k0,bounds=bnds,method='SLSQP',constraints=cons,options= ``````

{'maxiter':2000}) print(res)

I got k=1.1999 wich is a strange result, it does not satisfy the constraint. It should be `2` since `sum(assign(2))=0.52`. I also got a error message:

``  message: 'Iteration limit exceeded'``

OR
OR
Register

OR
Fill out the form below and instructions to reset your password will be emailed to you:

• Hire
• Post Projects

### Post Projects

• All at 0 Cost ....
• Post Tech Job
• Select Best Bidder
• Track the Project
• Approve Work and Pay safely
• Browse Nerds
• Work
• Find Projects Find Projects
• UI Design and UX
• Software Engineering
View more...
View less...
• Marketing
• General
• Manage
• Company Company

### Manage Company

• All at 0 Cost ....
• Manage Company and Employee Profiles
• Company wide Employee Productivity Reports
• Knowledge Sharing and Collaboration Tools
• Get Sales Lead and Bid for Tech Projects
• Send Invoices and Receive Payment Safely
• Learn
• Nerd Digest Nerd Digest
• UI Design and UX
• Software Engineering
View more...
View less...
• Marketing
• General
• Tech Q & A Tech Q & A
• UI Design and UX
• Software Engineering
View more...
View less...
• Marketing
• General