The operation of the NumPy power() function is applied element-wise. Think of it this way, the function takes the elements in the first array and matches them with its partner element in the second array. It then uses the component of the second array as the power.
Let us discuss this further.
The function syntax is as shown below:
The function parameters are discussed in the points below:
- x1 – refers to the input array whose elements act as the base in the power operation.
- x2 – defines the input array whose elements work as the exponent in the power operation.
NOTE: Although the shape of both arrays can be different, they must be broadcastable to a standard shape.
Function Return Value
As mentioned, the function returns an array with the elements of x1 raised to the power of x2 elements.
Consider the example shown below:
import numpy as np
x1 = np.array([1,2,3])
x2 = np.array([4,5,6])
In the example above, we start by importing NumPy with the alias as np.
Next, we create two arrays, x1 and x2. Finally, we use the power() function to return the elements of x1 raised to the power of elements in x2.
The resulting output is as shown:
The following example shows how to use the function with floating-point values.
x2 = np.array([6.7,8.9,10.1])
The code above should return an array as shown:
The same case applies when the function is used on a multi-dimensional array. An example is illustrated below:
x2 = np.array([[7,8,9], [10,11,12]])
The ab0ve code returns an array as shown:
[ 1048576 48828125 -2118184960]]
You can also raise the elements of first array with a common exponent as shown below:
In this example, we pass a single value instead of giving an array in the second variable. This value acts as the exponent for each element in the first array.
This should return:
[16 25 36]]
The function will return an error if the provided second array contain a negative value. An example is depicted below:
x2 = np.array([[-7,-8,9], [-10,-11,-12]])
The code above should return an error as shown:
NOTE: This error applies only if the exponent array contains a negative value.
This article covered how to use the power() function in NumPy. To explore further, check the docs.
Thanks for reading!!