Python Math copysign() Function Example
Python math copysign() is an inbuilt function of the Python math library that is used to get the float number with the sign of another number. The sign can be positive or negative. The math.copysign() is a function that exists in the Standard math Library of Python. The copysign() function returns a float value consisting of magnitude from parameter x and the sign (+ve or -ve) from parameter y.
Python Math copysign()
Python math module contains several mathematical operations, which can be performed with ease using the module. The math function returns the float with the magnitude (absolute value) of a but the sign of b.
Here x is the number which is to be converted to float, and y is the number whose sign will be copied to x.
Note: To call this function, we first have to import the math library.
copysign(10,-6): Here answer will be -10.0; it takes the sign from 6 and converting 10 to float.
The function takes two numbers, the first number can be integer or float and the second number is the number is whose sign is to be copied, finally it returns a float value by taking the sign from another number.
See the following code example.
# app.py import math # Taking two number from user x = int(input("Enter first number: ")) y = int(input("Enter second number: ")) # Now we will call copysign() function ans = math.copysign(x, y) # Printing the answer print("New value of x is: ", ans)
Enter first number: 15 Enter second number: -10 New value of x is: -15.0
In the above program, we have taken two integers x and y. Then we have called copysign() function, which converts x to float and copies the sign of y into x, and finally, we printed it.
See another code example.
# app.py import math def funCopy(): x = 11 y = -21 # implementation of copysign z = math.copysign(x, y) return z print(funCopy())
python3 app.py -11.0
Python copySign() Function Compatibility
Python 2.x – Yes Python 3.x – Yes
So, Python math.copysign() method is a library method of the math module, and it is used to get a number with the sign of another number, it accepts two numbers (either integers or floats) and returns a float value of the first number with the sign of the second number.