简体   繁体   中英

how to get scipy.optimize.linprog to keep going after an unsecessful termination

we have been tasked with checking a how many times a linear programming problem terminates successfully, however every time it fails it keeps me out of the loop, is there a way i can do the test and still continue with the next iteration?

from scipy.optimize import linprog
import numpy as np

#  objective function  maximum
f = [1 , 1 ]


result = []
hit = 0
miss = 0

for i in range(1000):

    norm1 = np.random.normal(-0.1,0.03) #a random value taken from the normal distribution mean=-0.1, 
std=0.03
    norm2 = np.random.normal(-0.4,1) # a random value taken from the normal distribution mean=-0.4, 
std=0.1
    #if norm1<0 and norm2<0:
    A = [ [ -0.12 , -0.04 ]  , [ norm1, norm2] ] 
    b = [-600  , -1000 ]

    x0_bounds = (None, None)
    x1_bounds = (None, None)

    # Find minimum

    res = linprog(f, A_ub=A, b_ub=b, bounds=(x0_bounds, x1_bounds ),
                  options={"disp": False})
    if res.success == True:
        hit+=1
        print("The amount to be invested = {:6.0f}" .format(res.fun) , "pounds" )
    else:
        miss+=1

print(hit)
print(miss)

Handling the exception did the trick for me. You can always tell Python how you would like to handle the exception as so: Let's say your except is a ValueError, this snippet of code could handle that exception for you.

try:
    res = linprog(f, A_ub=A, b_ub=b, bounds=(x0_bounds, x1_bounds),
                  options={"disp": False})
except ValueError:
    pass

This still allows the code to complete its loops, as necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM