简体   繁体   中英

Simple way to stop a number going negative

I have a simple exercise. I need to minus 2 tuples from each other but I dont want the result to go negative, I want to stop at 0. Similarly I want to add 2 tuples but I want to upper limit the value to 255.

So when I do (1,1,1)-(5,200,30) I should get the result (0,0,0) . And if I do (200,10,150)+(90,20,50) I should get (255,30,200) .

Are there any convenience functions in math or numpy that can do this?

Check clip in numpy

np.clip(np.array((1,1,1))-np.array((5,200,30)),a_min=0,a_max=255)
Out[186]: array([0, 0, 0])

You can do something like choose max of (the result or 0). That way if the result is negative, it will return 0 instead. For example:

t1 = (1,1,1)
t2 = (5, 200, 30)

for subtraction

[max(x[0]-x[1], 0) for x in zip(t1, t2)]

for addition

[min(x[0]+x[1], 255) for x in zip(t1, t2)]
def add(t1,t2):
    """
    input: t1,t2 are tuples.
    example t1(1,2,3) t2(7,8,9)
    result=(a=1+7,b=2+8,c=3+9)
    max of a, b, and c are 255
    """
    a=t1[0]+t2[0]
    b=t1[1]+t2[1]
    c=t1[2]+t2[2]
    if(a>255):
        a=255
    if(b>255):
        b=255
    if(c>255):
        c=255
    result=(a,b,c)
    return result

#CALLING
x=(1,1,1)
y=(5,200,30)
z=(200,10,150)
t=(90,20,50)


print(add(z,t))
(255, 30, 200)

A pure python way to clip values would be as follows:

>>> x = (25, 400, 30) 
>>> tuple(map(min, zip(x, (255,255,255))))
(25, 255, 30)

Likewise for lower limit:

>>> x = (25, -20, 30) 
>>> tuple(map(max, zip(x, (0,0,0))))
(25, 0, 30)

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