Constrain output values within a specified range

Question:

In this simple nested for loop, how can I in an elegant fashion set a constraint forcing a value to always within the range >0<1? If the lower or upper limit should be violated, then default to specified max or min values.

for factor in [1.2, 1.3]:
    for i in [0.8, 0.1, 0.5]:
        print(i*factor)
Output:
0.96
0.12
0.6
1.04
0.13
0.65
 
Asked By: Henrik

||

Answers:

If you want to silently force the variable in between 0 and 1 you can use min and max together like

min(1, max(0, i * factor))
Answered By: LTJ

You could use the min() and max() functions to cap any value between 0 and 1:

for factor in [1.2, 1.3]:
    for i in [0.8, 0.1, 0.5]:
        print(max(0, min(1, (i*factor))))
Answered By: Mathias R. Jessen
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.