w3resource

NumPy: Compute xy, element-wise where x, y are two given arrays


40. Element-wise Exponentiation (x^y)

Write a NumPy program to compute xy, element-wise where x, y are two given arrays.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating two arrays x and y
x = np.array([[1, 2], [3, 4]])
y = np.array([[1, 2], [1, 2]])

# Displaying the first array x
print("Array1: ")
print(x)

# Displaying the second array y
print("Array1: ")
print(y)

# Calculating the power of elements in array x raised to the power of elements in array y
r1 = np.power(x, y)

# Displaying the result of x raised to the power of y
print("Result- x^y:")
print(r1) 

Sample Output:

Array1: 
[[1 2]
 [3 4]]
Array1: 
[[1 2]
 [1 2]]
Result- x^y:
[[ 1  4]
 [ 3 16]]

Explanation:

In the above exercise –

x = np.array([[1, 2], [3, 4]]): This line initializes a two-dimensional NumPy array x with dimensions 2x2.

y = np.array([[1, 2], [1, 2]]): This line initializes a two-dimensional NumPy array y with dimensions 2x2.

r1 = np.power(x, y): Here, r1 will be a 2D NumPy array of the same shape as x and y, where each element of r1 is the corresponding element of x raised to the power of the corresponding element of y.


For more Practice: Solve these Related Problems:

  • Implement a function that computes element-wise exponentiation for two arrays using np.power.
  • Test the function on arrays with varied bases and exponents, including negative and fractional numbers.
  • Create a solution that uses broadcasting to handle cases where one array is a scalar and the other is an array.
  • Compare the output of np.power with a loop-based exponentiation for a set of test values to verify accuracy.

Go to:


PREV : Compute Reciprocals
NEXT : Element-wise Sign Indication

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.