math.copysign(x, y) returns a float with the magnitude (absolute value) of x and the sign of y.
Because it inspects the IEEE 754 sign bit of y directly, math.copysign(3.0, -0.0) returns -3.0 even though -0.0 == 0.0 is True.
math.copysign() is a function in Python's standard math module: import it with import math and call math.copysign(...), or import the name directly with from math import copysign.
Syntax
Import math and pass magnitude source x and sign source y.
python
import math
signed = math.copysign(x, y)
Call
What it does
math.copysign(3, -0.0)
Returns -3.0 (copies negative zero sign bit).
math.copysign(-5, 2)
Returns 5.0.
math.copysign(0.0, -4)
Returns -0.0.
math.copysign(4.5, float("-inf"))
Returns -4.5.
On Python versions without math.signbit(), math.copysign(1.0, x) < 0 is the standard way to test whether x has its sign bit set.
Function signatures
python
math.copysign(x, y, /)
# returns: float with |x| and sign bit of float(y)
Parameters
Parameter
Description
x
Required positional real number supplying the magnitude.
y
Required positional real number supplying the sign bit.
Return Value
Return Value
Description
float
Float combining fabs(x) with the sign bit of y.
Python Examples
Example 1 — Combine Magnitudes and Signs Including Negative Zero
Copy positive, negative, and negative-zero signs onto numbers as floats.
python
import math
print(math.copysign(3, -0.0))
print(math.copysign(-5, 2))
print(math.copysign(12.5, -1))
print(math.copysign(0.0, -7))
Output
-3.0
5.0
-12.5
-0.0
How It Works
Negative zero transfers minus. Passing -0.0 as y turns positive 3 into -3.0.
Positive strips minus. Passing 2 turns -5 into 5.0.
Creates signed zero. Copying a negative sign onto 0.0 produces -0.0.
Example 2 — Step a Slider Toward Any Target Without Branching
Move pos toward target by a fixed step size using math.copysign(step, target - pos).
python
import math
pos = 10.0
step = 2.5
for target in [25.0, 3.0, 10.0]:
delta = math.copysign(step, target - pos)
print(f"target={target:>4} -> delta={delta:+5.1f}")