Introduction Python Math Copysign() Method with Examples

Python copysign(x,y) function exists in Standard math Library of Python Programming Language. This function returns a float value consisting of magnitude from parameter x and the sign (+ve or -ve) from parameter y. This means the sign (+ve or -ve) of parameter y is attached to the magnitude of parameter x. For example if:

Python Math copysign()

Syntax:

math.copysign( x , y )

Parameters:

  • x is any valid Python number. This parameter is required.
  • y any valid Python number. This parameter is required.

Note: In copysign() function, both of the parameters are required.

Return Value

This function will return a float value which is consist of the absolute value or the magnitude of the parameter x and the sign of parameter y.

See the following code example.

Example 1


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

Output:

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.

Example 2

# app.py

import math


def funCopy():
    x = 11
    y = -21

    # implementation of copysign
    z = math.copysign(x, y)

    return z


print(funCopy())

Output

python3 app.py
-11.0

In these examples we can see 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.

Thanks for reading !

#python #programming

Introduction Python Math Copysign() Method with Examples
1 Likes10.85 GEEK