How to convert positive numbers to negative in Python?

How to convert positive numbers to negative in Python?

If you want to force a number to negative, regardless of whether its initially positive or negative, you can use:

    -abs(n)

Note that 0 will remain 0.

-abs(n) is a really good answer by Tom Karzes earlier because it works whether you know the number is negative or not.

If you know the number is a positive one though you can avoid the overhead of a function call by just taking the negative of the variable:

-n 

This may not matter much at all, but if this code is in a hot loop like a gameloop then the overhead of the function call will add add up.

>>> timeit.timeit(x = -abs(y), setup=y = 42, number=5000)
0.0005687898956239223
>>> timeit.timeit(x = -y, setup=y = 42, number=5000)
0.0002599889412522316

How to convert positive numbers to negative in Python?

I believe the best way would be to multiply each number by -1:

def negativeNumber(x):
    neg = x * (-1)
    return neg

Leave a Reply

Your email address will not be published. Required fields are marked *