0
0
NumPydata~5 mins

np.power() and np.square() in NumPy

Choose your learning style9 modes available
Introduction

We use np.power() and np.square() to quickly raise numbers or arrays of numbers to a power. This helps us do math easily on many numbers at once.

When you want to multiply a number by itself multiple times, like squaring or cubing.
When working with arrays of numbers and you want to raise each element to a power.
When calculating areas or volumes where powers are involved.
When preparing data for machine learning that needs power transformations.
When you want a simple way to square numbers without writing extra code.
Syntax
NumPy
np.power(base, exponent)
np.square(x)

np.power() takes two inputs: the base and the exponent.

np.square() is a shortcut to square numbers (raise to power 2).

Examples
Raises 3 to the power of 2, which is 9.
NumPy
np.power(3, 2)
Raises each element in the list to the power of 3: [1, 8, 27].
NumPy
np.power([1, 2, 3], 3)
Squares 4, result is 16.
NumPy
np.square(4)
Squares each element in the list: [4, 25, 49].
NumPy
np.square([2, 5, 7])
Sample Program

This program creates an array of numbers. It then cubes each number using np.power() and squares each number using np.square(). Finally, it prints all results.

NumPy
import numpy as np

# Using np.power to cube numbers
numbers = np.array([2, 3, 4])
cubed = np.power(numbers, 3)

# Using np.square to square numbers
squared = np.square(numbers)

print('Original numbers:', numbers)
print('Cubed:', cubed)
print('Squared:', squared)
OutputSuccess
Important Notes

np.power() can raise numbers to any power, not just integers.

np.square() is faster and simpler when you only need to square numbers.

Both functions work element-wise on arrays, so they apply the operation to each number separately.

Summary

np.power() raises numbers or arrays to any power you choose.

np.square() is a quick way to square numbers or arrays.

Both help you do math on many numbers easily and quickly.