How to Compute Square Roots in Python
Updated on May 12, 2025 | 20 min read | 13.31K+ views
Share:
For working professionals
For fresh graduates
More
Updated on May 12, 2025 | 20 min read | 13.31K+ views
Share:
Did you know? Introduced in Python 3.8, math.isqrt() returns the largest integer less than or equal to the square root of a non-negative number—without floating-point errors. It's ideal for exact calculations in cryptography and number theory. |
Python supports square root computation across real and complex domains using dedicated modules: math.sqrt() for real numbers, cmath.sqrt() for complex numbers, and math.isqrt() for exact integer results. For large-scale or array-based operations, libraries like NumPy offer vectorized square root functions optimized for performance.
This guide covers the key approaches to calculating square roots in Python, including integer approximation, floating-point precision, and complex number handling.
Boost your career with Online Data Science Courses by upGrad, now featuring a GenAI-integrated curriculum. Learn from top faculty at IIIT Bangalore and LJMU with globally recognized certification. Master Python, Machine Learning, AI, SQL, and Tableau — all built for real-world impact!
Calculating square roots in Python includes multiple methods , each designed for specific numeric types and use cases. Real numbers can be handled with math.sqrt(), integers with math.isqrt(), and complex numbers with cmath.sqrt(). This section outlines both built-in and library-based approaches, explaining how each method works and when to use it.
Strengthen your Python and data skills from the ground up. Advance your analytical edge with these expert-led programs that blend math, coding, and real-world problem solving:
Python’s math.sqrt() function is part of the built-in math module, which provides mathematical operations for real numbers. It is specifically used to compute the square root of non-negative real numbers, returning the result as a float.
How to Use math.sqrt()
First, you need to import the math module:
import math
result = math.sqrt(16)
print(result)
Output:
4.0
Explanation:
The square root of 16 is 4. math.sqrt() returns the result as a floating-point number (4.0), even though the input is an integer.
Another Example With a Float Input:
import math
result = math.sqrt(20.25)
print(result)
Output:
4.5
Explanation:
When the input is a float, the result remains a float. In this case, the square root of 20.25 is exactly 4.5.
What Happens With a Negative Input?
import math
result = math.sqrt(-9)
print(result)
Output:
ValueError: math domain error
Explanation:
math.sqrt() cannot compute the square root of a negative number because it only supports real number operations. Attempting this will raise a ValueError. If you need to work with negative values or complex numbers, use the cmath module instead.
In summary, use math.sqrt() when:
Pairing your expertise in Python and Docker with a certification from one of upGrad’s DBA programs from world-class B-Schools can help you move into C-Suite roles in technology. Along with earning a doctorate, you’ll publish original research and collaborate with industry leaders.
Python provides the cmath module to handle complex number arithmetic, including operations like computing the square root of negative numbers. Unlike the math module, which is limited to real numbers, cmath is built to work with both real and complex values. This makes it essential when dealing with operations that can result in imaginary or complex results.
Why Use cmath for Negative Inputs?
In mathematics, the square root of a negative number is not defined in the real number system. For example, √–16 does not have a real result, but in the complex number system, it is defined as 4i (represented in Python as 4j). The cmath.sqrt() function correctly returns a complex result when given a negative input, avoiding the ValueError you’d get from math.sqrt().
Basic Example With a Negative Number
import cmath
result = cmath.sqrt(-16)
print(result)
Output:
(5+0j)
Explanation:
Even though 25 is a real number, cmath.sqrt() still returns a complex number format: (5+0j). The +0j indicates that the imaginary part is zero. This is because cmath always returns a complex type, regardless of the input.
Example With a Complex Input:
import cmath
result = cmath.sqrt(3 + 4j)
print(result)
Output:
(2+1j)
Explanation:
cmath.sqrt() correctly computes the square root of a complex number. In this case, √(3 + 4j) equals (2+1j). The result is another complex number, represented with both real and imaginary components.
Use cmath.sqrt() when:
Also Read: Python Cheat Sheet: From Fundamentals to Advanced Concepts for 2025
The math.isqrt() function computes the integer square root of a non-negative integer. That means it returns the floor of the exact square root—essentially the largest integer n such that n² is less than or equal to the input.
Unlike math.sqrt(), which returns a float, math.isqrt() always returns an integer and avoids any floating-point operations. This makes it particularly useful in contexts where exact values are required and precision cannot be compromised.
Use Cases for math.isqrt()
Basic Example With a Non-Perfect Square:
import math
result = math.isqrt(10)
print(result)
Output:
3
Explanation:
The exact square root of 10 is approximately 3.16. math.isqrt(10) returns 3—the integer part, or floor value, of the square root without any decimal or rounding error.
Example With a Perfect Square:
import math
result = math.isqrt(36)
print(result)
Output:
6
Explanation:
Since 36 is a perfect square, math.isqrt(36) returns 6 exactly. The function does not convert the result to a float; it stays as an integer.
Error Handling With Negative Inputs
import math
result = math.isqrt(-9)
print(result)
Output:
ValueError: isqrt() argument must be nonnegative
Explanation:
math.isqrt() only accepts non-negative integers. If a negative value is passed, Python raises a ValueError.
Python Version Requirement
math.isqrt() was introduced in Python 3.8. If you are using an earlier version, this function will not be available. You can check your Python version with:
import sys
print(sys.version)
Use math.isqrt() when:
Interested in taking your Python skills to the next level? This Executive Diploma in Machine Learning and AI with Python helps you master advanced concepts like Deep Learning, NLP, and MLOps, equipping you to build optimized and scalable AI solutions.
In Python, you can compute square roots using the exponentiation operator **. Raising a number to the power of 0.5 is a shorthand way to get its square root. This method is simple and doesn’t require importing any modules, making it useful for quick calculations.
Basic Example:
result = 25 ** 0.5
print(result)
Output:
5.0
Explanation:
Here, 25 ** 0.5 returns 5.0, the square root of 25. The result is a float, even though the input is an integer. This method uses Python’s built-in arithmetic operators.
Example With a Non-Perfect Square
result = 10 ** 0.5
print(result)
Output:
3.1622776601683795
Explanation:
The square root of 10 is an irrational number. This expression returns a floating-point approximation. It’s fast and works without any imports.
Pros and Cons of Using ** 0.5
Pros:
Cons:
result = (-9) ** 0.5)
print(result)
Output:
ValueError: math domain error
(Note: In reality, this can raise a TypeError or return nan depending on the context, so behavior may be inconsistent.)
Use the ** 0.5 approach when:
Also Read: Essential Skills and a Step-by-Step Guide to Becoming a Python Developer
NumPy is a powerful numerical computing library widely used in data science, machine learning, and scientific computing. One of its strengths is vectorized operations, which allow you to perform mathematical computations on entire arrays without writing explicit loops. The np.sqrt() function is a prime example—it efficiently computes square roots of all elements in an array at once.
Basic Example With an Array:
import numpy as np
result = np.sqrt([1, 4, 9, 16])
print(result)
Output:
[1. 2. 3. 4.]
Explanation:
np.sqrt() takes a list of numbers, converts it into a NumPy array (if it isn't already), and returns a new array containing the square roots of each element. This operation is fully vectorized, meaning it executes much faster than looping through elements manually, especially with large datasets.
Performance on Large Datasets
import numpy as np
arr = np.arange(1_000_000)
result = np.sqrt(arr)
Explanation:
This code generates an array with one million elements and computes their square roots in a single, optimized operation. NumPy’s internal C-based implementation makes this orders of magnitude faster than using a Python for loop with math.sqrt().
Data Type Handling
np.sqrt() returns a NumPy array of float values by default, even if the input is integers. If any input value is negative, the result will be nan unless the input is explicitly cast to a complex type.
import numpy as np
result = np.sqrt([-1, 4])
print(result)
Output:
[nan 2.]
Explanation:
Unlike cmath.sqrt(), NumPy’s default behavior for negative inputs is to return nan, not a complex number. To handle complex results, convert the input to a complex type:
result = np.sqrt(np.array([-1, 4], dtype=complex))
print(result)
Output:
[0.+1.j 2.+0.j]
Use np.sqrt() when:
While Python provides several built-in methods to calculate square roots, implementing one manually—such as using Newton’s Method—can offer valuable insight into how square root algorithms work under the hood. This is especially useful for educational purposes or when building systems where full control over the algorithm is required.
Newton’s Method for Square Roots
Newton’s Method is an iterative numerical approach used to approximate the roots of a function. To compute the square root of a number x, you repeatedly apply the formula:
You continue the process until the guess is close enough to the actual square root.
Python Implementation
def custom_sqrt(x, tolerance=1e-10):
if x < 0:
raise ValueError("Cannot compute square root of a negative number")
guess = x / 2.0
while abs(guess * guess - x) > tolerance:
guess = 0.5 * (guess + x / guess)
return guess
# Test the function
print(custom_sqrt(16)) # Output: 4.0
print(custom_sqrt(20)) # Output: ~4.4721
Explanation:
Use Cases and Learning Value
Now that you've seen how each method works, here's a quick comparison to help you choose the right one for your use case.
The table below compares all major square root methods in Python, focusing on what types of inputs they support, the kind of outputs they return, example usage, and when to choose each method.
Method |
Input Type |
Output Type & Example |
Best Use Case |
math.sqrt() | Non-negative real numbers | float → math.sqrt(25) → 5.0 | General-purpose square root for real numbers |
cmath.sqrt() | Real and complex (incl. negatives) | complex → cmath.sqrt(-9) → 3j | Working with complex numbers and negative roots |
math.isqrt() | Non-negative integers | int → math.isqrt(10) → 3 | Exact integer square roots, useful in cryptography |
** 0.5 | Real numbers (non-negative) | float → 9 ** 0.5 → 3.0 | Quick inline use, less precise and no error handling |
np.sqrt() | Arrays of real or complex numbers | array → np.sqrt([1, 4]) → [1. 2.] | Fast, vectorized computation on large datasets |
Notes:
You can enhance your knowledge with practical applications of Python with upGrad’s Learn Basic Python Programming. It covers fundamental coding concepts, including conditional statements, looping syntax, and operators in Python.
Square root calculations play a vital role across domains like physics, finance, and data science. Below are five practical applications, each tied to common problems solved with Python.
1. Distance Calculation Using the Pythagorean Theorem
In physics and geometry, the Pythagorean theorem is used to calculate the straight-line distance between two points. This principle underpins GPS systems, game development, and robotics pathfinding.
import math
x1, y1 = 0, 0
x2, y2 = 3, 4
distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
print(distance) # Output: 5.0
Example: A drone navigating between waypoints uses this to compute the shortest path across a coordinate grid.
2. Standard Deviation in Financial Risk Analysis
Standard deviation measures how much a set of financial returns deviate from the mean—used to assess portfolio risk or stock volatility.
import numpy as np
returns = [0.01, 0.02, -0.01, 0.005]
std_dev = np.sqrt(np.mean((np.array(returns) - np.mean(returns)) ** 2))
print(std_dev)
Example: An investment analyst evaluates which asset is more volatile before allocating capital.
3. Root Mean Square Error (RMSE) in Model Evaluation
In machine learning, RMSE quantifies the difference between predicted and actual values. It’s often used in regression models to evaluate prediction accuracy.
import numpy as np
actual = np.array([3, 5, 2.5])
predicted = np.array([2.5, 5, 4])
rmse = np.sqrt(np.mean((actual - predicted) ** 2))
print(rmse)
Example: A data scientist uses RMSE to compare the performance of two housing price prediction models.
4. Feature Normalization in Machine Learning Pipelines
Square root scaling is occasionally used in preprocessing pipelines to dampen the effect of large feature values without losing too much data variance.
import numpy as np
feature = np.array([1, 4, 9, 16])
normalized = np.sqrt(feature)
print(normalized) # Output: [1. 2. 3. 4.]
Example: In an image recognition task, features representing pixel intensity might be square root scaled before being fed into a neural network.
5. Euclidean Distance for Clustering Algorithms
In k-means clustering or k-nearest neighbors (k-NN), the square root function helps compute Euclidean distances between feature vectors
import numpy as np
point_a = np.array([1, 2])
point_b = np.array([4, 6])
distance = np.sqrt(np.sum((point_a - point_b)**2))
print(distance) # Output: 5.0
Example: An e-commerce platform uses k-NN to recommend products by measuring distance between user preference vectors.
To compute square roots in Python effectively, match the method to your use case: use math.sqrt() for basic real numbers, cmath.sqrt() for complex input, math.isqrt() for exact integers, ** 0.5 for quick inline calculations, and np.sqrt() for large arrays. Choose precision, performance, or readability based on what your application demands.
Many developers can write the code, but few understand when and why to use each method in data-intensive, production-grade applications. That’s where upGrad bridges the gap—through structured learning, hands-on projects, and mentorship tailored for tech careers in data, AI, and software engineering.
Explore in-demand courses by upGrad:
Not sure how to upskill in your career path? Get personalized career counseling to identify the best opportunities for you. Visit upGrad’s offline centers for expert mentorship, hands-on workshops, and networking sessions to connect you with industry leaders!
Expand your expertise with the best resources available. Browse the programs below to find your ideal fit in Best Machine Learning and AI Courses Online.
Discover in-demand Machine Learning skills to expand your expertise. Explore the programs below to find the perfect fit for your goals.
Discover popular AI and ML blogs and free courses to deepen your expertise. Explore the programs below to find your perfect fit.
Reference Link:
https://realpython.com/python-square-root-function
900 articles published
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology s...
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Top Resources