r/inventwithpython • u/sm_050 • Nov 07 '19
how to convert an if-else statement to a linear programming constraint in Python
I have two variables E[i] and Y[i], where E is a continuous variable and Y is binary.So the condition is:
if E[i] <= rmin:
Y[i]==1
else:
Y[i]==0How do I convert this if-else loop to linear constraint using Python.
3
Nov 07 '19
This is just a general comment based on observations from reading code suggestions on sites such as Reddit and Stack Overflow. It seems like those who make code suggestions don’t actually test the code before making the suggestion. They make a suggestion based on what they think will work instead of what proves to work.
1
u/Jackeea Nov 08 '19
I actually tested mine and it works fine though? Casting a boolean to an integer worked for me.
1
1
u/DuckSaxaphone Nov 08 '19
I think
Y=np.where(E<=rmin,1,0)Is your best option since it abandons the need for a loop to populate Y. It works if E is a numpy array, otherwise you need to do E=np.asarray(E) then the above.
You'll probably find whatever you're doing works better with Y and E as nparrays anyway.
2
u/Jackeea Nov 07 '19
Y[i] = int(E[i] <= rmin)