Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
NumPy power()
In this tutorial, you will learn about the numpy.power() method with the help of examples.
The power() function is used to raise the elements of an array to a specified power.
Example
import numpy as np
# create an array for the base values
base = np.array([2, 3, 4])
# create an array for the exponent values
exponent = np.array([2, 3, 4])
# use power() to raise the base values to the power of the corresponding exponent values
result = np.power(base, exponent)
print(result)
# Output : [ 4 27 256]
power() Syntax
The syntax of power() is:
numpy.power(base, exponent, out=None)
power() Arguments
The power() function takes one argument:
base- the input array containing base valuesexponent- the exponent value or array, which can be a scalar or an array of the same shape asbase.out(optional) - the output array where the result will be stored
power() Return Value
The power() function returns an array that contains the elements of the base array raised to the power of the corresponding elements in the exponent array.
Example 1: power() With Scalar Exponent
import numpy as np
# create an array for the base values
base = np.array([1, 2, 3, 4, 5])
# specify the exponent value
exponent = 3
# use power() to raise the base values to the specified exponent
result = np.power(base, exponent)
print(result)
Output
[ 1 8 27 64 125]
In this example, we have used the power() function to raise each element in the base array to the power of the specified exponent.
Example 2: power() With Array of Exponent Values
import numpy as np
# create an array for the base values
base = np.array([2, 3, 4])
# create an array for the exponent values
exponent = np.array([4, 2, 1])
# use power() to raise the base values to the power of the corresponding exponent values
result = np.power(base, exponent)
print(result)
Output
[16 9 4]
Example 3: Use of out Argument in power()
import numpy as np
base = np.array([7, 8, 9, 10, 12])
exponent = 2
# create an empty array with the same shape as the base array
result = np.zeros_like(base)
# calculate the power and store the result in the out_array
np.power(base, exponent, out=result)
print(out_array)
Output
[ 49 64 81 100 144]
Here, after specifying out=result, the result of the power operation is stored in the result array.