NumPy | Get the Powers of Array Values Element-Wise
Last Updated :
09 Feb, 2024
To calculate the power of elements in an array we use the numpy.power() method of NumPy library.
It raises the values of the first array to the powers in the second array.
Example:
Python3
import numpy as np
sample_array1 = np.arange( 5 )
sample_array2 = np.arange( 0 , 10 , 2 )
print ( "Original array " )
print ( "array1 " , sample_array1)
print ( "array2 " , sample_array2)
power_array = np.power(sample_array1, sample_array2)
print ( "power to the array1 and array 2 : " , power_array)
|
Output:
Original array
array1 [0 1 2 3 4]
array2 [0 2 4 6 8]
power to the array1 and array 2 : [ 1 1 16 729 65536]
Syntax
Syntax: numpy.power(arr1, arr2, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None)
Parameters:
- arr1: Input array or object which works as base.Â
- arr2: Input array or object which works as exponent.Â
- out: Output array with same dimensions as Input array, placed with the result.Â
- where: [array_like, optional]True value means to calculate the universal functions(ufunc) at that position, False value means to leave the value in the output alone.
More Examples
Let’s look at more Python programs that shows how to find the Power of elements in the array using the power() function of the NumPy library.
Example 1: Computing the same power for every element in the array.
Python3
import numpy as np
array = np.arange( 8 )
print ( "Original array" )
print (array)
print ( "power of 3 for every element-wise:" )
print (np.power(array, 3 ))
|
Output:
Original array
[0 1 2 3 4 5 6 7]
power of 3 for every element-wise:
[ 0 1 8 27 64 125 216 343]
Example 2: Computing the power of decimal value.
Python3
import numpy as np
sample_array1 = np.arange( 5 )
sample_array2 = [ 1.0 , 2.0 , 3.0 , 3.0 , 2.0 ]
print ( "Original array " )
print ( "array1 " , sample_array1)
print ( "array2 " , sample_array2)
power_array = np.power(sample_array1, sample_array2)
print ( "power to the array1 and array 2 : " , power_array)
|
Output:
Original array
array1 [0 1 2 3 4]
array2 [1.0, 2.0, 3.0, 3.0, 2.0]
power to the array1 and array 2 : [ 0. 1. 8. 27. 16.]
Note: you can not compute negative power
Example 3: Computing negative power
Python3
import numpy as np
array = np.arange( 8 )
print ( "Original array" )
print (array)
print ( "power of 3 for every element-wise:" )
print (np.power(array, - 3 ))
|
Output:
Share your thoughts in the comments
Please Login to comment...