Python math.copysign() Method



The Python math.copysign() method returns a floating-point number with the magnitude (absolute value) of the first argument and the sign of the second argument. Mathematically, it can be represented as −

copysign(x,y) = |x|.sign(y)

Where, |x| represents the absolute value of x, and sign(y) represents the sign of y. For example, if x is 5 and y is -3, then math.copysign(5, -3) will return -5, because it takes the magnitude of 5 and applies the sign of -3 to it, resulting in -5.

The math.copysign() method is useful when you want to change the sign of a number while preserving its magnitude or when you want to set the sign of a number based on another value.

Syntax

Following is the basic syntax of the Python math.copysign() method −

math.copysign(x, y)

Parameters

This method accepts the following parameters −

  • x − This is a numeric value whose magnitude will be used in the result.

  • y − This is a numeric value whose sign will be used in the result.

Return Value

The method returns a float, which has the magnitude of x and the sign of y. If both x and y are integers, the return value will also be an integer.

Example 1

In the following example, we are copying the sign of "-1" to the magnitude of "10" using the copysign() method −

import math
result = math.copysign(10, -1)
print("The result obtained is:",result) 

Output

The output obtained is as follows −

The result obtained is: -10.0

Example 2

Here, we are copying the sign of 0 to the magnitude of 5. Since the sign of zero is positive, the result will be a positive integer value −

import math
result = math.copysign(5, 0)
print("The result obtained is:",result) 

Output

Following is the output of the above code −

The result obtained is: 5.0

Example 3

In this example, we use variables "magnitude" and "sign" to demonstrate how you can copy the sign of one value to another −

import math
magnitude = 5
sign = -1
result = math.copysign(magnitude, sign)
print("The result obtained is:",result) 

Output

We get the output as shown below −

The result obtained is: -5.0

Example 4

The math.copysign() method preserves the sign of the second argument, regardless of the magnitude of the first argument.

This example copies the sign of 1 to the magnitude of -15, resulting in 15.0. Even though the magnitude is negative, the sign is overridden to be positive −

import math
result = math.copysign(-15, 1)
print("The result obtained is:",result) 

Output

The result produced is as shown below −

The result obtained is: 15.0
python_maths.htm
Advertisements