0
0
NumpyHow-ToBeginner ยท 3 min read

How to Use sqrt in NumPy: Simple Guide with Examples

Use numpy.sqrt() to calculate the square root of a number or each element in an array. Pass a single number or a NumPy array as the argument, and it returns the square root(s).
๐Ÿ“

Syntax

The basic syntax of numpy.sqrt() is simple:

  • numpy.sqrt(x): Calculates the square root of x.
  • x can be a single number or a NumPy array.
  • The function returns the square root of each element if x is an array.
python
import numpy as np

np.sqrt(x)
๐Ÿ’ป

Example

This example shows how to use numpy.sqrt() with a single number and with an array of numbers.

python
import numpy as np

# Square root of a single number
single_value = 16
sqrt_single = np.sqrt(single_value)

# Square root of an array
array_values = np.array([1, 4, 9, 16, 25])
sqrt_array = np.sqrt(array_values)

print(f"Square root of {single_value}: {sqrt_single}")
print(f"Square roots of {array_values}: {sqrt_array}")
Output
Square root of 16: 4.0 Square roots of [ 1 4 9 16 25]: [1. 2. 3. 4. 5.]
โš ๏ธ

Common Pitfalls

Common mistakes when using numpy.sqrt() include:

  • Passing negative numbers, which results in nan (not a number) because square root of negative numbers is not defined for real numbers.
  • For complex numbers, you need to use numpy.lib.scimath.sqrt() to get correct results.

Example of wrong and right usage:

python
import numpy as np

# Wrong: sqrt of negative number returns nan
neg_value = -4
print(np.sqrt(neg_value))  # Output: nan

# Right: use scimath.sqrt for complex results
from numpy.lib import scimath
print(scimath.sqrt(neg_value))  # Output: 2j
Output
nan 2j
๐Ÿ“Š

Quick Reference

FunctionDescription
numpy.sqrt(x)Returns square root of x (number or array)
numpy.lib.scimath.sqrt(x)Returns square root, supports negative and complex numbers
InputNumber or NumPy array
OutputSquare root(s) as float or complex
โœ…

Key Takeaways

Use numpy.sqrt() to find square roots of numbers or arrays easily.
Passing negative numbers to numpy.sqrt() returns nan; use numpy.lib.scimath.sqrt() for complex results.
Input can be a single number or a NumPy array for element-wise square roots.
The output is a float or array of floats representing the square roots.
Always import numpy as np before using numpy.sqrt().