NumPy: Compute xy, element-wise where x, y are two given arrays
NumPy Mathematics: Exercise-40 with Solution
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.
Python-Numpy Code Editor:
Previous: Write a NumPy program to compute the reciprocal for all elements in a given array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/numpy/python-numpy-math-exercise-40.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics