0
0
NumpyHow-ToBeginner ยท 3 min read

How to Use Power Function in NumPy for Exponentiation

Use the numpy.power(base, exponent) function to raise each element of base to the power of exponent. Both base and exponent can be numbers or arrays of the same shape or broadcastable shapes.
๐Ÿ“

Syntax

The numpy.power function has the following syntax:

  • numpy.power(base, exponent)

base: A number or array containing the base values.

exponent: A number or array containing the exponents to raise the base to.

The function returns an array where each element is base[i] raised to exponent[i].

python
numpy.power(base, exponent)
๐Ÿ’ป

Example

This example shows how to use numpy.power to raise numbers and arrays to powers.

python
import numpy as np

# Raise a single number to a power
result1 = np.power(3, 4)  # 3^4 = 81

# Raise each element of an array to a power
arr = np.array([2, 3, 4])
result2 = np.power(arr, 3)  # each element to the power 3

# Raise elements of one array to powers from another array
exponents = np.array([1, 2, 3])
result3 = np.power(arr, exponents)  # 2^1, 3^2, 4^3

print(result1)
print(result2)
print(result3)
Output
81 [ 8 27 64] [ 2 9 64]
โš ๏ธ

Common Pitfalls

Common mistakes when using numpy.power include:

  • Passing arrays of different shapes without broadcasting compatibility, which causes errors.
  • Using negative bases with fractional exponents, which can result in complex numbers or errors.
  • Confusing numpy.power with the ** operator; while both work, numpy.power supports array inputs explicitly.
python
import numpy as np

# Wrong: arrays with incompatible shapes
try:
    np.power(np.array([1, 2]), np.array([3, 4, 5]))
except ValueError as e:
    print(f"Error: {e}")

# Right: compatible shapes or scalars
result = np.power(np.array([1, 2]), 3)
print(result)
Output
Error: operands could not be broadcast together with shapes (2,) (3,) [1 8]
๐Ÿ“Š

Quick Reference

ParameterDescription
baseNumber or array to be raised to a power
exponentNumber or array representing the power to raise to
ReturnArray with each element as base^exponent
โœ…

Key Takeaways

Use numpy.power(base, exponent) to raise numbers or arrays to powers element-wise.
Both base and exponent can be scalars or arrays of the same shape or broadcastable shapes.
Watch out for shape mismatches and negative bases with fractional exponents.
numpy.power is preferred for array exponentiation over the ** operator for clarity.