NumPy | power method
Start your free 7-days trial now!
power(~) method is used to compute the power of each number of the input array.
power(~) method uses the same data-type as the input array to perform the calculation; if your input array only contains integers, then returned result will also be of type
int. On the other hand,
float_power(~) always uses
float64 for maximum precision.
The base numbers.
Instead of computing the power of all the numbers, we can choose specific numbers. Values corresponding to
True will be considered, while those corresponding to
False values will be ignored.
A scalar if
x1 is a scalar, otherwise a NumPy array is returned.
Use the ** syntax instead whenever possible. Instead of using
np.power([1,2,3],2), simply use
[1,2,3]**2, which offers a huge performance boost. The only case when you'd want to use this
power(~) method is when you have multiple exponents.
Using a common exponent
To raise the the numbers by a common exponent, provide a scalar:
np.power([1,2,3], 2)array([1, 4, 9])
Using multiple exponents
You can pass an array as the exponents as well:
np.power([1,2,3], [2,3,4])array([ 1, 8, 81])
What we are doing here is computing
Using a mask
We can choose which values to take power of by providing a boolean mask, like follows:
np.power([2,3,4], 2, where=[False, True, False])array([1, 9, 3])
Notice how only the values that are flagged as
True in the boolean masks are considered (i.e. the value 3 in this case).