AppDividend
Latest Code Tutorials

Numpy power: How to Use np.power() Function in Python

Numpy is an extremely robust, and very solid library for data science in Python. The numpy power() function treats elements in the first input array as a base and returns it raised to the power of the corresponding component of the second input array.

Numpy power

The numpy.power() is a mathematical function in Python that is used to get one array that contains elements of the first array raised to the power element of the second array. The numpy power() function takes two main arguments: 1) The array of base 2).

The np.power() returns the array with elements of the first array raised to the power element of the second array. This means if we have two arrays ( must be of the same size ) arr1 and arr2, then numpy.power() will calculate arr1i^arr2i for each  i=0 to size_of_arrary-1. If values of arr2 are not positive, then this function will return a ValueError.

Syntax

numpy.power(arr_of_base, arr_of_exp, out = None, 
            where = True, casting = ‘same_kind’, 
            order = ‘K’, dtype = None) 

Parameters

  1. arr_of_base: This is the first array whose elements work as a base. As implies, the argument to this arr_of_base parameter should be the array of numbers. These integers will be used as the “bases” of our exponents.
  2. arr_of_exp: This is the second array whose elements work as an exponent. This parameter enables you to specify the exponents that you will apply to the bases, array-of-bases. Note that just like the array-of-exponents input, this input must be the Numpy array or an array-like object. So here, you can provide the NumPy array, a Python list, a tuple, or another Python object with array-like properties. You can even provide a single integer.
  3. out: This is a ndarray and an optional field. A place the result will be stored in. If given, the shape to which the inputs broadcast must be in. When a freshly allocated array is returned unless received or None. A tuple (possible as a keyword argument only) must have a length equal to the outputs. 
  4. where: This state is transmitted over data. The out array will be set to an ufunc result in locations where the condition is True. The out array will be maintaining its original interest elsewhere. Notice that if the default out = None produces an uninitialized out list, positions within it where the condition is False will remain uninitialized.

Return Value

NumPy power() function returns an array with elements of the first array raised to the power element of the second array. The result will be in integer form.

Program to show the working of power()

See the following code.

#Importing numpy
import numpy as np

#Declaring arr1 and arr2
arr1 = [4, 2, 1, 6, 5]
arr2 = [4, 0, 5, 2, 3]

#Now we will check working of power()
print("Elements of arr1 raised to the power elements of arr2 are: ")
print(np.power(arr1, arr2))

Output

Elements of arr1 raised to the power elements of arr2 are:
[256   1   1  36 125]

Explanation

In this program, we have first declared two arrays of the same shape, and all are integers, as you can see. 

Then we have called numpy.power() to calculate arr1^iarr2i.

So, according to the formula, we got our desired output.

Negative power in Numpy

Should we use the negative exponent with NumPy power? The answer is No. The np.power() doesn’t work with negative exponents. If you try to use the negative power then it will throw ValueError: Integers to negative integer powers are not allowed.

See the following code.

# Program to show ValueError when elements of arr2 are negative

# Importing numpy
import numpy as np

# Declaring arr1 and arr2
arr1 = [4, 2, 1, 6, 5]
arr2 = [4, 0, -5, 2, -3]

# Now we will check working of power()
print("Elements of arr1 raised to the power elements of arr2 are: ")
print(np.power(arr1, arr2))

Output

Elements of arr1 raised to the power elements of arr2 are:
Traceback (most recent call last):
  File "app.py", line 12, in <module>
    print(np.power(arr1, arr2))
ValueError: Integers to negative integer powers are not allowed.

Explanation

In this program, we have first declared two arrays of the same shape, and all are integers, as you can see. Then we have called numpy.power() to calculate arr1i^arr2i. But as said above, this function returns a ValueError when elements of the second array are negative, and we got a ValueError.

Numpy power of Matrix

To find the power of Matrix in numpy, we have to use the numpy.linalg.matrix_power(a, n) function. 

For positive numbers n, the power is computed by repeated matrix squaring and the matrix multiplications.

If n == 0, then the identity matrix of the same shape as M is returned.

If n < 0, the inverse is computed and then raised to the abs(n).

See the following code.

# app.py

import numpy as np

data = np.array([[0, 1], [-1, 0]])
op = np.linalg.matrix_power(data, 3)
print(op)

Output

 python3 app.py
[[0 -1]
 [1 0]]

 Let’s see another example.

# app.py

import numpy as np

data = np.array([[0, 1], [-1, 0]])
op = np.linalg.matrix_power(data, 0)
print(op)

Output

python3 app.py
[[1 0]
 [0 1]]

Numpy power vs **

Is there a difference between numpy.power() and using the ** operator on a Numpy array? The answer is Yes, there is a time execution difference between these two approaches.

import numpy as np
import time

arr1 = np.array([[21, 19], [11, 18]])
arr2 = np.array([[11, 18], [21, 19]])

first_start_time = time.time()
print(np.power(arr1, arr2))
print("The execution time for np.power() method: ",
      time.time() - first_start_time)

second_start_time = time.time()
print(arr1 ** arr2)
print("The execution time for ** approach: ", time.time() - second_start_time)

 Output

[[ 350277500542221 -4519998179177339479]
[ 3105570700629903195 -8946610666848387072]]

The execution time for np.power() method: 0.0004169940948486328

[[ 350277500542221 -4519998179177339479]
[ 3105570700629903195 -8946610666848387072]]

The execution time for ** approach: 0.00032711029052734375

You can see that the difference between the first and second approaches is execution time. The ** approach is slightly faster than the np.power() method.

Conclusion

The np.power() function computes exponents in Numpy. Python numpy.power() function enables us to perform the simple exponentiation like b to the power of n, and it also allows you to do this with large Numpy arrays. We have seen how to find the power of the np array and find the power of Matrix.

Finally, the Numpy power() function example is over.

See also

Numpy roll()

Numpy eye()

Numpy npv()

Numpy fv()

Numpy pv()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.