How to Find Square Root in Python: Techniques Explained
Updated on Aug 26, 2025 | 18 min read | 13.83K+ views
Share:
For working professionals
For fresh graduates
More
Updated on Aug 26, 2025 | 18 min read | 13.83K+ views
Share:
Did you know? Rabin cryptosystem, used for encryption in your online messages, relies on complex square root problems to protect data, making it incredibly difficult to hack. Thanks to Python’s powerful math tools, your information remains safe and secure! |
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.
These square root functions are valuable in real-life applications, such as physics simulations, finance, and signal processing, where accurate calculations are crucial. However, many developers struggle with errors when trying to compute the square roots of negative numbers or large integers.
This guide covers the key approaches on how to compute square roots in Python, including integer approximation, floating-point precision, and complex number handling.
Popular AI Programs
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.
Ready to start coding? Enroll in the Basic Python Programming course by upGrad. In just 12 hours, you'll learn Python fundamentals, solve practical problems, and earn a certificate. Start today!
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.
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.
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.
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 Cases for math.isqrt()
Machine Learning Courses to upskill
Explore Machine Learning Courses for Career Progression
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.)
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]
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
Output:
4.000000000000004
4.472135954999956
Explanation:
Use Cases and Learning Value
Also Read: Math for Data Science: A Beginner’s Guide to Important Concepts
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:
Understanding how to compute square roots in Python and choosing the right method ensures both accuracy and efficiency. With that in mind, let’s explore how this technique is used in real-life scenarios to solve complex problems.
Subscribe to upGrad's Newsletter
Join thousands of learners who receive useful tips
When learning how to compute square roots in Python, it’s not just about performing simple calculations; it’s about applying this knowledge to solve complex, real-life problems.
Here are some practical applications where knowing how to compute square roots in Python is crucial:
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
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 further deepen your Python skills, consider exploring topics such as data manipulation with NumPy, optimization techniques, or machine learning algorithms that also rely heavily on mathematical functions.
Mastering square roots in Python is essential for both beginners and advanced developers. From basic calculations with math.sqrt() to handling complex numbers via cmath.sqrt(), integer roots with math.isqrt(), or vectorized computations using NumPy, Python offers versatile methods to suit every requirement.
Understanding how to compute square roots in Python empowers you to solve real-world problems, including distance calculations, risk analysis, and machine learning preprocessing. Choosing the right method ensures accuracy, efficiency, and code reliability. With these techniques, you can confidently implement square root operations in Python for both simple tasks and advanced applications.
Many developers find it difficult to 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.
In addition to the courses mentioned above, here are some more free courses that can help you enhance your skills:
Feeling uncertain about your next step? 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.
References:
https://arxiv.org/html/2506.09569v1
https://crypto.stackexchange.com/questions/85851/how-to-decrypt-rabin-message-when-p-q-and-you-have-the-roots-from-tonelli-shanks
https://www.csa.iisc.ac.in/~arpita/Cryptography15/CT11.pdf
When working with loops or large datasets, using math.sqrt() repeatedly can slow down performance. For best efficiency, especially in numerical analysis or real-time systems, switch to NumPy’s np.sqrt() function. It applies square root operations to entire arrays at once using vectorized execution, which is significantly faster than looping over individual elements. Converting your list to a NumPy array first ensures compatibility and optimal speed. This method is ideal for processing thousands or millions of values quickly.
Yes, square root functions are commonly used in game development to scale values in a balanced, non-linear way. For example, you might use square roots to calculate diminishing returns for XP, smooth out difficulty curves, or normalize distances in movement algorithms. Python’s math.sqrt() works well for real-time logic, especially in smaller games or scripts. For large-scale or multiplayer games, optimize by caching results or precomputing common values to maintain performance without losing accuracy.
If your application requires whole number square root values, you can combine round() with math.sqrt() to achieve this. This approach is useful in educational tools, simple games, or user-facing applications where decimals aren't needed. For strictly downward rounding without decimals, use math.isqrt() to return only the integer part of the square root. Just make sure your input is non-negative, as neither function handles negative values or complex input without throwing an error.
To apply square roots to a column in a Pandas DataFrame, use np.sqrt(df['column']) for fast, vectorized computation. This method is widely used in data preprocessing pipelines for scaling features or calculating derived metrics. If your column contains negative values, np.sqrt() will return NaN for those entries. To handle this, either clean your data beforehand or use .clip(lower=0) to reset negative values to zero before applying the square root transformation.
Yes, if you want to manually compute square roots in Python—perhaps for learning or control—you can implement Newton’s Method in Python. This iterative approach refines an estimate until it's close to the true square root. While not as fast or precise as Python’s built-in options, it's a great way to understand how root-finding algorithms work. Just remember to include input validation, stopping criteria, and safeguards against infinite loops or negative values when implementing your custom function.
For real-time or near-real-time applications like sensor feeds or financial tickers, performance and efficiency matter. Use np.sqrt() with pre-converted NumPy arrays to take full advantage of its speed and batch processing capabilities. Avoid for-loops and math.sqrt() when working with large volumes of streaming data. Also consider caching previously computed values or using just-in-time compilation tools like Numba for further speed improvements when square root computations are a performance bottleneck.
In image processing, square root functions are used in contrast enhancement, normalization, and filtering techniques. For example, computing the square root of pixel intensity values can help reduce brightness extremes while preserving structural features. This is particularly useful in medical imaging, satellite data, or low-light enhancement tasks. Using np.sqrt() ensures that transformations are efficiently applied to entire image arrays, making it compatible with libraries like OpenCV, PIL, or directly within NumPy/Pandas pipelines.
To conditionally apply square root operations—say, only to positive numbers—you can use np.where() or list comprehensions in Python. For example, np.where(x > 0, np.sqrt(x), 0) calculates roots only when values are positive and substitutes zero otherwise. This is common in data cleansing, financial modeling, and fault-tolerant systems. It helps prevent errors like ValueError or NaN from invalid inputs while maintaining predictable output behavior across large datasets or input streams.
Absolutely. You can wrap Python’s square root logic in a custom function to add validation, default behavior, or conditional processing. This is especially useful when integrating square root logic into larger systems, data pipelines, or APIs. For example, you can write a function that accepts numbers, lists, or arrays, checks for negative values, and returns appropriate results or error messages. This adds clarity, reduces code repetition, and simplifies debugging across your project.
In machine learning and data analysis, square roots in Python are used in distance calculations—especially for clustering and outlier detection. Euclidean distance, which requires a square root, helps quantify how far a point is from a cluster center or mean. Anomalies often appear as items with unusually high distance scores. By combining this with z-scores or residual analysis, you can build reliable models that detect data drift, fraud, or system faults with greater confidence.
Not directly. User input must always be validated and sanitized before applying mathematical operations like square roots. Ensure the input is numeric and non-negative to avoid ValueError or unexpected crashes. Use try/except blocks to handle invalid values, and consider applying type checks, regex validation, or form-level constraints in web or GUI applications. Secure coding practices are essential when working with inputs that might originate from users or external sources.
For negative values, use cmath.sqrt() or cast NumPy arrays to complex types. This returns results as complex numbers, avoiding ValueError. This method is essential for scientific computing, engineering, or simulations where negative inputs occur, ensuring accurate handling of complex or imaginary roots.
Yes. NumPy’s np.sqrt() efficiently calculates square roots on entire arrays simultaneously. Vectorization eliminates Python loops, improves memory efficiency, and accelerates computation, making it ideal for machine learning pipelines, large-scale simulations, and high-performance numerical processing.
Standard deviation measures data dispersion. Python computes it as the square root of the variance. Using np.sqrt() on mean-squared differences enables precise calculation. This is crucial in finance, statistics, and data science for assessing risk, volatility, and variability efficiently across datasets.
Absolutely. Euclidean distance involves summing squared differences between points and taking the square root. It’s widely applied in k-NN, clustering, or anomaly detection. Efficient computation with NumPy ensures rapid processing for large datasets, enabling machine learning models to operate effectively in real-world applications.
Yes. Cache frequently computed roots or use precomputed lookup tables for recurring values. Combined with NumPy vectorization or JIT compilation tools like Numba, this approach significantly reduces computation time in loops, streaming data, or performance-critical applications.
Square roots are used to compute distances, velocities, energies, and other physical quantities. Functions like math.sqrt(), cmath.sqrt(), or np.sqrt() provide accurate, efficient calculations for simulations, robotics, or trajectory analysis in Python-based physics engines.
Yes. Square roots can be part of larger calculations, like RMSE, normalized scoring, or physics formulas. NumPy ensures vectorized execution, while Python’s math module provides precision for single-value operations. Proper order of operations and input validation ensures reliable outcomes.
Use try/except blocks for ValueError or invalid inputs. Check for negatives and handle complex numbers with cmath or cast arrays to complex types. Proper error handling maintains program stability, prevents crashes, and ensures consistent results across datasets.
Yes. Square roots are used to calculate volatility, risk, RMSE, and scaling of financial data. Applying np.sqrt() on arrays or Pandas Series allows vectorized computation, ensuring fast, accurate analysis for portfolio evaluation, asset comparison, or predictive financial modeling.
900 articles published
Pavan Vadapalli is the Director of Engineering , bringing over 18 years of experience in software engineering, technology leadership, and startup innovation. Holding a B.Tech and an MBA from the India...
Speak with AI & ML expert
By submitting, I accept the T&C and
Privacy Policy
Top Resources