Overview
- The function copysign() from the math module, when passed a magnitude(m) and a number(ss) as a sign source, the function copies the sign from ss to m.
- Python does not have a sign() function. Simulating sign() function using copysign() is possible in two ways:
- Give a negative number as ss and 1 as m to copysign(), which will return -1.
- Give a positive number as ss and 1 as m to copysign(), which will return 1.
Example 1
# Example program that copies a sign from another number
# for a given number and returns a float
import math
# Copy the sign of a positive number to a negative number
v = math.copysign(-4, 3)
print(v)
# Copy the sign of a negative number to a positive number
v = math.copysign(4, -3)
print(v)
# Copy the sign of a negative number to a negative number
v = math.copysign(-4.1, -4)
print(v)
print(type(v))Output
4.0
-4.0
-4.1
<class 'float'>Example 2
# Example Python program simulating sign function
import math
# Sign(negative quantity)
magnitude = 1
signSource = -4
value = math.copysign(magnitude, signSource)
print(value)
# Sign(postive quantity)
magnitude = 1
signSource = 4
value = math.copysign(magnitude, signSource)
print(value)Output
-1.0
1.0