Active October 08, 2021 / Viewed 594 / Comments 0 / Edit

Examples of how to get the sign of a number (e.g -1 or +1) in python:

Let's consider the following variables in python:

`x1 = 42`

`x2 = -24`

To get the sign of those numbers a solution is to use the function copysign(x, y) from python's math module:

`import math`

`math.copysign(1,x1)`

will returns:

`1`

while

`math.copysign(1,x2)`

will returns:

`-1`

copysign(a,b) gives the sign of b and the absolute value of a, So for example:

`math.copysign(-4,2)`

gives

`4`

Create a function sign

`sign = lambda x: math.copysign(1, x)`

then

`x = 42`

`sign(x)`

gives

`1`

Another example

`x = -24`

`sign(x)`

gives

`-1`

Another example, try to create your own function

`def mysign(x):`

`if x >= 0:`

`return 1`

`else:`

`return -1`

Then

`x = 42`

`print( mysign(x) )`

gives

`1`

while

`x = -24`

`print( mysign(x) )`

gives

`-1`

Ads

License

This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
Ads

Ads