Python math.copysign() method “returns a float value consisting of magnitude from parameter x and the sign (+ve or -ve) from parameter y.”
- x: It is the number to be converted to float
- y: It is the number whose sign will be copied to x.
Note: We must first import the math library to call this function.
copysign(10,-6): Here answer will be -10.0; it takes the sign from 6 and converts 10 to float.
The function takes two numbers, the first number can be an integer or float, and the second number is the number whose sign is to be copied finally. It returns a float value by taking the sign from another number.
Example 1: How to Use math.copysign() Method
import math x = int(input("Enter first number: ")) y = int(input("Enter second number: ")) ans = math.copysign(x, y) print("New value of x is: ", ans)
Enter first number: 15 Enter second number: -10 New value of x is: -15.0
Example 2: How does the math.copysign() method work?
import math def funCopy(): x = 11 y = -21 # implementation of copysign z = math.copysign(x, y) return z print(funCopy())
Example 3: Copy magnitude (negative number) and sign (negative number)
import math x = -9 y = -5 result = math.copysign(x, y) print('copysign(x, y) :', result)
copysign(x, y) : -9.0
Example 4: Copy magnitude (positive number) and sign (positive number)
import math x = 12 y = 6 result = math.copysign(x, y) print('copysign(x, y) :', result)
copysign(x, y) : 12.0