Pythonic way to constrain variable ranges?

Is there a better way to do this?

if a > 1:
    a = 1
if a < 0:
    a = 0

      

I was thinking about using a function because I have a lot of them in my code.I was curious if there was a clearer way to do this.

+3


source to share


2 answers


What you are describing is usually called clipping. There are several ways to do cropping.

Library ( numpy

)

You can use numpy.clip

for this:

numpy.clip (a, a_min, a_max, out = None)

So:

import numpy

numpy.clip(x,0,1)

      

Although, since Python function calls are expensive and numpy

typically batch process data, for a single value it will introduce computational overhead.

For example:

>>> x = -2.5
>>> numpy.clip(x,0,1)
0.0
>>> x = 2.5
>>> numpy.clip(x,0,1)
1.0
>>> x = 0.5
>>> numpy.clip(x,0,1)
0.5

      



You usually use numpy

to do operations on (large) matrices , for example if you need to process a 1000x1000 matrix and using numpy

it will definitely pay off.

Pure Python

A pure python approach can be obtained with

max(0,min(1,x))

      

But here you have two calls , as a result it will be slower than using operators if

.

Finally, if you stick with the code if

, you can optimize it with elif

:

if x < 0:
    x = 0
elif x > 1:
    x = 1

      

Or a more general function:

def clip(x,min,max):
    if x < min:
        return min
    elif x > max:
        return max
    return x

      

+8


source


I will always use something like max(0, min(1, x))

. If x is greater than 1, it min(1, x)

will be equal to 1, and max(0, 1)

- 1. If x is less than 0, it min(1, x)

will be x

, but it max(0, x)

will be 0.



+4


source







All Articles