NumPy, which stands for “Numerical Python,” is a basic package that is mostly used with arrays and multidimensional matrices. A broad variety of functions are available in this open-source package to carry out intricate mathematical operations on arrays or matrices.
One such mathematical function is the
sign() function in the NumPy package, it is used to return the sign for each individual element of the given input array. Let us try to understand this function, its syntax, and its implementation in Python.
What is the NumPy sign() function used for?
This function returns the sign indicative of the input value/s. The return type of this function is an n-dimensional array with output values. The output values are as follows:
- If x – input, is a real number.
- for x > 0, the output is 1
- for x = 0, the output is 0
- for x < 0, the output is -1
- If x – input, is a complex number.
- if x.real is not 0, the output is the sign of x.real + 0j
- if x.real is 0, the output is the sign of x.imaginary + 0j
- For NaN (not a number) input, the output is also NaN.
numpy.sign(x, /, out=None, *, where=True)
- x: array, required
- Input values.
- out: n-dimensional array, optional
- a place where the outcome is saved. It must have a shape that the inputs broadcast to if it is provided. A newly allocated array is returned in the absence of any input or None. The length of a tuple must match the number of outputs.
- where: array_like, optional
- This circumstance is announced over the input. The ufunc result will be set to the out array at points where the condition is True. The out array will keep its initial value in all other places. It should be noted that locations inside an uninitialized out array formed using the default = none will continue to be uninitialized if the condition is False.
- **kwargs, optional
- For other keyword-only arguments.
Implementing the NumPy sign() method
Make sure to import the NumPy package in your IDE before implementing the function. To do so run the following line of code in your IDE.
import numpy as np
Example 1: Real numbers as Input
x1 = (4, -10) np.sign(x1) x2 = (-0.002, 13.2, 4/3) np.sign(x2) #checking sign of zero np.sign(0)
Example 2: Complex Numbers as Input
#x.real is non-zero x = np.sign(2 - 5j) y = np.sign(-4 - 7j) print(x,"\n",y) #x.real is zero x = np.sign(-2j) y = np.sign(+5j) print(x,"\n",y)
Note: In presence of the real part of the complex number, the sign of the imaginary part doesn’t matter. Only in the cases where the real part is equal to zero the sign of the imaginary part is taken into consideration.
The mathematical functions in NumPy, like the one discussed in this article- the sign() function makes mathematical operations on arrays and multi-dimensional arrays much more efficient. The sign function will always return a scalar value for scalar input. To learn more about the NumPy package and python in general click here!