Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to limit ranges on a variable?

Is there a better way to do this?

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

I was thinking of using a function because I have a lot of these in my code, Was curious if there was a shorter comprehensible way to do it.

like image 802
Ishaan Patel Avatar asked Jun 15 '17 09:06

Ishaan Patel


People also ask

How do you limit a number in a range in Python?

limit-number.pydef limit(num, minimum=1, maximum=255): """Limits input 'num' between minimum and maximum values. Default minimum value is 1 and maximum value is 255.

How do you clamp a variable in Python?

clamp() method clamps all the input elements into the range [ min, max ] and return a resulting tensor. inp: This is input tensor. min: This is a number and specifies the lower-bound of the range to which input to be clamped. max: This is a number and specifies the upper-bound of the range to which input to be clamped.


2 Answers

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

Library (numpy)

You can use numpy.clip for that:

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

So:

import numpy

numpy.clip(x,0,1)

Although since function calls in Python are expensive, and numpy usually processes data in batch, for a single value it will result in 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

Usually you use numpy to perform operations on (large) matrices, for instance if you have to process a 1000x1000 matrix, than using numpy 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 if statements.

Finally if you stick with the if-code, you can optimize it a tiny bit by using an elif:

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

Or a more generic function:

def clip(x,min,max):
    if x < min:
        return min
    elif x > max:
        return max
    return x
like image 87
Willem Van Onsem Avatar answered Oct 20 '22 01:10

Willem Van Onsem


I'd always use something like max(0, min(1, x)). If x is more than 1, min(1, x) will be 1, and max(0, 1) is still 1. If x is less than 0, min(1, x) will be x, and max(0, x) will be 0.

like image 39
acdr Avatar answered Oct 20 '22 00:10

acdr