← Back to NumPy Course | Chapter 6: Math Operations | Lesson 7 of 7

np.power/sqrt

power raises numbers to exponents and sqrt takes square roots, for every element at once.

In this page:

  1. np.power/sqrt
Syntax
python
np.power(a, n)
np.sqrt(a)

np.power/sqrt

np.power(a, n) is the function form of a ** n and also accepts an array of exponents. np.sqrt returns square roots, and np.cbrt cube roots. Taking sqrt of negative floats gives nan with a warning; use complex dtype if needed.

Note: np.square(a) is a fast shortcut for a ** 2.

Example: np.power/sqrt

python
import numpy as np

a = np.array([1, 2, 3, 4])
print(np.power(a, 3))
print(np.power(2, a))
print(np.sqrt(a).round(3))
print(np.cbrt(np.array([8, 27])))

# Output:
# [ 1  8 27 64]
# [ 2  4  8 16]
# [1.    1.414 1.732 2.   ]
# [2. 3.]
Related Topics
Common Mistakes
  1. Taking the square root of negative numbers
  2. Integer powers with negative exponents raising an error
  3. Confusing np.power with np.exp
Chapter Summary
  • np.power matches the ** operator
  • Exponents can be arrays
  • sqrt of negatives gives nan
  • np.square and np.cbrt are shortcuts
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.