Python math.copysign() - Copy Sign


Python math.copysign()

math.copysign(x, y) function returns a float formed using the magnitude of x and sign of y.

If your platform supports signed zeroes, then the sign of -0.0 is also considered.

Syntax

The syntax to call copysign() function is

math.copysign(x, y)

where

ParameterRequiredDescription
xYesA float value.
yYesA float value.

Examples

1. Copy magnitude (of positive number) and sign (of negative number)

Copy sign of y=-4 and magnitude (absolute value) of x=8.

Python Program

import math

x = 8
y = -4
result = math.copysign(x, y)
print('copysign(x, y) :', result)

Output

copysign(x, y) : -8.0

2. Copy magnitude (of negative number) and sign (of positive number)

x is negative and y is positive.

Python Program


x = -8
y = 4
result = math.copysign(x, y)
print('copysign(x, y) :', result)

Output

copysign(x, y) : 8.0

3. Copy magnitude (of negative number) and sign (of negative number)

x is negative and y is negative.

Python Program

import math

x = -8
y = -4
result = math.copysign(x, y)
print('copysign(x, y) :', result)

Output

copysign(x, y) : -8.0

4. Copy magnitude (of positive number) and sign (of positive number)

x is positive and y is positive.

Python Program

import math

x = 8
y = 4
result = math.copysign(x, y)
print('copysign(x, y) :', result)

Output

copysign(x, y) : 8.0

Summary

In this Python Math tutorial, we learned the syntax of, and examples for math.copysign() function.