np.power(base, exponent) computes base raised to exponent for each pair of elements, supporting a scalar exponent applied to every element, an array of matching shape for per-element exponents, or the usual broadcasting rules for compatible-but-different shapes. Raising a negative base to a fractional exponent, or an integer base array to a negative integer exponent, can produce nan or raise an error depending on dtype, since the mathematical result may not be a real number, or may not fit the array's integer type.
1Understanding np.power()
np.power(base, exponent) computes base raised to exponent for each pair of elements, supporting a scalar exponent applied to every element, an array of matching shape for per-element exponents, or the usual broadcasting rules for compatible-but-different shapes. Raising a negative base to a fractional exponent, or an integer base array to a negative integer exponent, can produce nan or raise an error depending on dtype, since the mathematical result may not be a real number, or may not fit the array's integer type.
Raising an integer array to a negative power raises a ValueError, since NumPy can't represent a fractional result in an integer array — convert to a float dtype first if you need negative or fractional exponents.
import numpy as np
base = np.array([1, 2, 3, 4])
print(np.power(base, 2))2Practical Example
Here is a real-world application of np.power() showing how it is used in production NumPy code.
import numpy as np
base = np.array([2, 3, 4])
exponents = np.array([1, 2, 3])
print(np.power(base, exponents))3Best Practices
Follow these guidelines when working with np.power():
1. Convert to a float dtype before using negative or fractional exponents, since integer arrays can't represent the resulting fractional values
2. Use np.sqrt(x) instead of x ** 0.5 for square roots specifically, since it's more explicit about intent and can be marginally faster
3. Watch for nan results when raising negative bases to fractional exponents, since the mathematical result isn't a real number in that case
Tip: Raising an integer array to a negative power raises a ValueError, since NumPy can't represent a fractional result in an integer array — convert to a float dtype first if you need negative or fractional exponents.
import numpy as np
base = np.array([1, 2, 3, 4])
print(np.power(base, 2))