How to reduce any number not equal to 0 to 1 and any number equal to 0 kept at 0 in Python? [closed]

The first behaviour you list is mathematically called the signum operation. If you are allowed to use numpy, i’d simply do:

import numpy
sign = numpy.sign(x)

With regard to your 2nd question, that’s quite easy.

Simply use:



With some tinkering i found a solution for your first question, too:

negsign = int(int(num) >> 31)
possign = int(num > 0)

sign = negsign + possign

Note that i did not thoroughly test this for special cases like -0.

Browse More Popular Posts

Leave a Comment