all Python 3Numbers & mathfunction
math.copysign
representation
Return a value with the magnitude of x and the sign of y, including the sign of -0.0.
Syntax
math.copysign(...)
Its least obvious use is telling 0.0 from -0.0: comparison cannot do it, since -0.0 == 0.0 is True, but math.copysign(1, x) returns -1.0 precisely for negative zero. The sign is read straight from the sign bit, so it also works on nan and infinities, and the result is always a float even when both arguments are ints.
Examples
import math
print(math.copysign(3, -1)) # → -3.0
print(math.copysign(-3, 1)) # → 3.0
x = -12.5
print(math.copysign(1, x)) # → -1.0
print(math.copysign(2, -0.0)) # → -2.0
See also
Open in the full glossarydocs.python.orgReport an inaccuracy