Python copysign

The Python copysign function is used to find the absolute value of the first argument. This copysign function returns the absolute value along with the sign specified in the second argument.

Python copysign Syntax

The syntax of the copysign Function in Python Programming Language is

Math.copysign(x, y);
  • X: Please specify the X value here. The Function finds the absolute value of this argument.
  • Y: Please specify the X value here. It uses this argument sign (Positive or Negative) and returns the output.

For example, if x = 2.45 and Y = -5.40, then math.copysign(2.45, -5.40) = -2.45. It is because the absolute value of 2.45 is 2.45, and the second argument sign is Negative, so the output is -2.45

NOTE: If the X value or Y value argument is not a number, the copysign function returns TypeError.

Python copysign Function Example

The copysign function returns the absolute value of the first argument, along with the sign specified in the second argument. In this example, We are going to find the copysign of different data types and display the output.

import math

Tup = (10.98, 20.26, 12.05, -40.95 , 50.45) # Tuple Declaration
Lis = [-10.98, 32.65, -39.59, -42.15 , 15.97] # List Declaration

print('Calculating CopySign of Positive Number = %.2f' %math.copysign(2, 3))
print('Calculating CopySign of Negative Number = %.2f' %math.copysign(-2, 3))

print('Calculating CopySign of Positive Decimal = %.2f' %math.copysign(5.63, -3.0))
print('Calculating CopySign of Negative Decimal = %.2f' %math.copysign(-2.48, 1.15))

print('Calculating Power of of Tuple Item = %.2f' %math.copysign(Tup[2], 2.25))
print('Calculating Power of of Tuple Item = %.2f' %math.copysign(Tup[2], -2.25))
print('Calculating Power of List Item = %.2f' %math.copysign(Lis[4], 4.5))
print('Calculating Power of List Item = %.2f' %math.copysign(Lis[4], -4.5))

print('Calculating CopySign of Multiple Number = %.2f' %math.copysign(1 + 2 - 12.65, 2))

print('Calculating CopySign of String Value = ', math.copysign('2', 3))
Python COPYSIGN Function

In this program

  1. Within the first two statements, We passed both the Positive integer and negative integer as the Python copysign Function arguments. From the above screenshot, you see that it is returning output.
  2. Within the next two Python statements, We passed both the Positive and negative decimal values as the arguments. As you see, the method is returning output.
  3. For the following four statements, We used the Tuple and List items as the first arguments and Positive and negative decimals as the second argument for this Math function. If you observe the above screenshot, this method is working perfectly on them.
  4. We assigned multiple values as the first arguments, which worked without issue.
  5. Last, we tried this Function on the String value, which returns TypeError.