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 # Copy the sign of a positive number to a negative number # Copy the sign of a negative number to a positive number # Copy the sign of a negative number to a negative number |
Output:
4.0 -4.0 -4.1 <class 'float'> |
Example 2:
# Example Python program simulating sign function # Sign(negative quantity) # Sign(postive quantity) |
Output:
-1.0 1.0 |