Change the sign of a value to that of another in Numpy

NumpyServer Side ProgrammingProgramming

To change the sign of a value to that of another, use the numpy.copysign() method in Python Numpy. The 1st parameter of the copysign() is the value to change the sign of. The 2nd parameter is the sign to be copied to 1st parameter value.

The out is a location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

The condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.

Steps

At first, import the required library −

import numpy as np

Change the sign of a value to that of another, use the numpy.copysign() method in Python Numpy. Checking for integer −

print("Result? ", np.copysign(0, 1))
print("
Result? ", np.copysign(0, -1))

Checking for float −

print("
Result? ", np.copysign(14., -1))
print("
Result? ", np.copysign(-3.6, 1))

Checking for NaN −

print("
Result? ", np.copysign(np.nan, -1))
print("
Result? ", np.copysign(np.NAN, 1))

Checking for infinity −

print("
Result? ", np.copysign(np.inf, -1))
print("
Result? ", np.copysign(np.NINF, -1))

Checking for log −

print("
Result? ", np.copysign(np.log(1), 1))
print("
Result? ", np.copysign(np.log(2), -1))

Example

import numpy as np

# To change the sign of a value to that of another, use the numpy.copysign() method in Python Numpy
# The 1st parameter of the copysign() is the value to change the sign of.
# The 2nd parameter is the sign to be copied to 1st parameter value.
print("Result? ", np.copysign(0, 1))
print("
Result? ", np.copysign(0, -1))

# Checking for float
print("
Result? ", np.copysign(14., -1))
print("
Result? ", np.copysign(-3.6, 1))

# Checking for NaN
print("
Result? ", np.copysign(np.nan, -1))
print("
Result? ", np.copysign(np.NAN, 1))

# Checking for infinity
print("
Result? ", np.copysign(np.inf, -1))
print("
Result? ", np.copysign(np.NINF, -1))

# Checking for log
print("
Result? ", np.copysign(np.log(1), 1))
print("
Result? ", np.copysign(np.log(2), -1))

Output

Result? 0.0

Result? -0.0

Result? -14.0

Result? 3.6

Result? nan

Result? nan

Result? -inf

Result? -inf

Result? 0.0

Result? -0.6931471805599453
raja
Updated on 08-Feb-2022 11:11:49

Advertisements