.sqrt()

MamtaWardhani's avatar
Published Jun 6, 2024Updated Apr 9, 2025
Contribute to Docs

The .sqrt() function computes the positive square root of all elements in the input array. As a universal function (ufunc), it operates element-wise and returns an array of the same shape with square root values.

Widely used in fields like statistics, physics, engineering, and machine learning, .sqrt() is a powerful tool for performing efficient mathematical operations on numerical arrays of various shapes and data types.

Syntax

numpy.sqrt(x, out=None, where=True, casting='same_kind', order='K', dtype=None)

Parameters:

  • x: The input array or scalar value for which to compute the square root.
  • out (Optional): The output array where the result will be stored. Must have the same shape as input if provided.
  • where (Optional): Boolean array or condition indicating where to calculate the sqrt. By default, it computes the sqrt for all elements (True).
  • casting (Optional): Controls what kind of data casting may occur during computation.
  • order (Optional): Memory layout of the output array.
  • dtype (Optional): Data type of the output array.

Return value:

The function returns an array of the same shape as x, containing the positive square root of each element in the input array.

Example 1: Basic Square Root Calculation

This example demonstrates how to use NumPy’s .sqrt() function to calculate the square root of each element in a 1D array:

import numpy as np
# Create a 1D array
array1 = np.array([4, 9, 16, 25])
# Calculate square root of each element
result = np.sqrt(array1)
# Display the result
print("Original array:", array1)
print("Square root result:", result)

The output generated by this code is:

Original array: [ 4 9 16 25]
Square root result: [2. 3. 4. 5.]

The .sqrt() function processes each element independently, computing the square root and returning a new array with the results. Note that the output array contains floating-point numbers even if the input contains integers.

Example 2: Computing Standard Deviation with .sqrt()

This example shows how to use the .sqrt() function in statistical calculations, specifically to compute the standard deviation of a dataset:

import numpy as np
# Sample data points
data = np.array([2, 4, 6, 8])
# Calculate the mean
mean = np.mean(data)
# Calculate deviations from the mean
deviations = data - mean
# Square the deviations
squared_dev = deviations ** 2
# Calculate the variance (mean of squared deviations)
variance = np.mean(squared_dev)
# Compute standard deviation using sqrt()
std_deviation = np.sqrt(variance)
print("Dataset:", data)
print("Mean:", mean)
print("Variance:", variance)
print("Standard Deviation:", std_deviation)
# Compare with NumPy's built-in function
print("NumPy's std function result:", np.std(data))

The output of this code is:

Dataset: [2 4 6 8]
Mean: 5.0
Variance: 5.0
Standard Deviation: 2.236067977499790
NumPy's std function result: 2.236067977499790

This example demonstrates how the .sqrt() function is used in computing standard deviation, a common statistical measure that indicates how spread out values are from the mean.

Codebyte Example: Working with Complex and Negative Numbers

This code demonstrates how NumPy’s .sqrt() function operates on 2D arrays, negative values, and with conditional application using the where parameter:

Code
Output
Loading...

The example shows that .sqrt() works element-wise on 2D arrays, maintaining their shape. For negative numbers, it returns nan along with a warning, unless complex handling is specified. The where parameter allows selective square root computation based on a condition, such as non-negative values.

FAQs

1. What happens when I apply `.sqrt()` to negative numbers?

By default, NumPy's `.sqrt()` returns `nan` and raises a warning when applied to negative numbers in real-valued arrays. To compute square roots of negative numbers, convert the input to a complex data type.

2. Can I use `.sqrt()` with arrays of different data types?

Yes, NumPy automatically promotes data types as needed. However, be aware that the return type might differ from the input type, typically returning floating-point numbers.

3. What's the difference between [`math.sqrt()`](https://www.codecademy.com/resources/docs/python/math-module/math-sqrt) and `numpy.sqrt()`?

`math.sqrt()` works only on scalar values, while `numpy.sqrt()` works on both scalars and arrays, applying the operation element-wise to arrays.

All contributors

Contribute to Docs

Learn Python:NumPy on Codecademy