copysign() function - Python math module

The math module of python has a copysign() function. It copies the sign of one number(ss) to another number(m) and returns the result as a float.

Math Updated 20 Aug 2021 1 min read

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

python
# 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

Output
4.0

-4.0

-4.1

<class 'float'>

Example 2

python
# 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

Output
-1.0

1.0