w3resource

NumPy: Get the powers of an array values element-wise

NumPy Mathematics: Exercise-5 with Solution

Write a NumPy program to get the powers of an array values element-wise.

Note: First array elements raised to powers from second array.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating an array from 0 to 6
x = np.arange(7)

# Displaying the original array
print("Original array:")
print(x)

# Raising the elements of the array to the power of 3 and displaying the result
print("First array elements raised to powers from second array, element-wise:")
print(np.power(x, 3)) 

Sample Output:

Original array                                                         
[0 1 2 3 4 5 6]                                                        
First array elements raised to powers from second array, element-wise: 
[  0   1   8  27  64 125 216]

Explanation:

In the above exercise –

x = np.arange(7): This line creates a NumPy array that includes numbers from 0 to 6.

print(np.power(x, 3)): This line takes the above array and raises each element to the power of 3. The output of this code will be a new NumPy array where each element is the cube of the corresponding element in the original x array. That is, it would output the array [0, 1, 8, 27, 64, 125, 216].

Pictorial Presentation:

NumPy Mathematics: Get the powers of an array values element-wise

Python-Numpy Code Editor:

Previous: Write a NumPy program to get the largest integer smaller or equal to the division of the inputs.
Next: Write a NumPy program to get the element-wise remainder of an array of division.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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-5.php