简体   繁体   中英

Function in python that outputs either -1 or 0 or 1

Is there like a (modified) round function where the output would be either -1,0,1 depending on to what number is the input the closest? Eg 0 => 0, -2154 => -1, 10 => 1

Currently I am using normal if else statements:

if (i==0):
    return 0
elif i > 0: 
    return 1
else:
    return -1

But is there any way how I can make this a one-line code? By for instance using some modified round function.

You can use numpy.sign()

import numpy as np

print(np.sign(1.2))
print(np.sign(-3.4))
print(np.sign(0))

output:

1.0
-1.0
0

Without any imports:

def sign(i):
    return (i>0) - (i<0)
    
print(sign(1))
print(sign(-3))
print(sign(0))

output:

1
-1
0

Here is a one-liner function using plain vanilla python and no imports. It can hardly get simpler than this.

def f(i):
    return -1 if i < 0 else int(bool(i))


In [5]: f(0)
Out[5]: 0

In [6]: f(1)
Out[6]: 1

In [7]: f(-5)
Out[7]: -1

As the other answer commented, you can do it easily by using the numpy.sign() method, that directly returns your desired result.

However, you can do it directly using the built-in math function and the method copysign(x, y) , which copies the sign of the second value to the first. By setting the first value as a boolean it will be interpreted as 0 if the original value is 0, and 1 otherwise. Then we copy the sign of value, which will transform the 1 into -1 or leave it positive.

from math import copysign

values = [1, 200, 0, -3, 45, -15]

for value in values:
    print(int(copysign(bool(value), value)))

which outputs:

1
1
0
-1
1
-1

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