np.power/sqrt
power raises numbers to exponents and sqrt takes square roots, for every element at once.
In this page:
Syntax
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
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
- Taking the square root of negative numbers
- Integer powers with negative exponents raising an error
- 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: