Python math.copysign() Method

  1. Syntax
  2. Parameters
  3. Returns
  4. Examples
Python math.copysign() Method

Python math.copysign() method is an efficient way of finding the magnitude from parameter x and the sign (+ or -) from parameter y.

Syntax

math.copysign(x, y)

Parameters

x Any integer value.
y Any integer value whose sign we need.

Returns

This method’s return type is a float value representing the new value, made up of a magnitude of x and a sign of y.

Examples

Use of Python math.copysign() Method Without Function

Code Snippet:

import math

x = 7
y = -6
value = math.copysign(x, y)
print(f"The magnitude of {x} & sign of {y} returns the value of {value}.")

x = -8
y = -6
value = math.copysign(x, y)
print(f"The magnitude of {x} & sign of {y} returns the value of {value}.")

x = -9
y = 1
value = math.copysign(x, y)
print(f"The magnitude of {x} & sign of {y} returns the value of {value}.")

Output:

The magnitude of 7 & sign of -6 returns the value of -7.0.
The magnitude of -8 & sign of -6 returns the value of -8.0.
The magnitude of -9 & sign of 1 returns the value of 9.0.

For better understanding, assume that the value is returned with the magnitude, absolute value of a but the sign of b.

Use of Python math.copysign() Method With Function

Code Snippet:

import math


def func(x, y):
    value = math.copysign(x, y)
    return value


print(func(10, -10))

Output:

-10.0

Note that you can enter a floating point number as a parameter too.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Musfirah Waseem avatar Musfirah Waseem avatar

Musfirah is a student of computer science from the best university in Pakistan. She has a knack for programming and everything related. She is a tech geek who loves to help people as much as possible.

LinkedIn

Related Article - Python Math