How to Find Square Root in Python: Techniques Explained

By Pavan Vadapalli

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.

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-life impact!

Square Root Calculation Methods in Python

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:

1. Using math.sqrt() for Real Numbers

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!

2. Handling Complex Numbers With cmath.sqrt()

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

3. Integer Square Roots With math.isqrt

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  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 squaremath.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()

  • CryptographyAlgorithms often require integer square roots for primality testing or modular arithmetic without floating-point rounding.
  • Integer-only algorithms: Useful in embedded systems or performance-critical code where floating-point math is less efficient or unavailable.
  • Memory-efficient computation: Returns only the integer part, saving you from managing floating-point overhead.

Machine Learning Courses to upskill

Explore Machine Learning Courses for Career Progression

360° Career Support

Executive PG Program12 Months
background

Liverpool John Moores University

Master of Science in Machine Learning & AI

Double Credentials

Master's Degree18 Months

Interested in taking your Python skills to the next level? This Executive Diploma in Machine Learning and AI with Python helps you grasp advanced concepts like Deep Learning, NLP, and MLOps, equipping you to build optimized and scalable AI solutions.Start today!

4. Using the Exponentiation Operator (**)

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:

Here25 ** 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:

  • No imports needed — built-in syntax.
  • Works with both integers and floats.
  • Useful for quick scripts or inline calculations.

Cons:

  • Slightly less precise than math.sqrt() due to how floating-point arithmetic is handled.
  • No error handling for complex or negative inputs — raises a ValueError if the number is negative:
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

5. Using NumPy’s np.sqrt() for Arrays and Performance

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]

6. Creating a Custom Square Root Function

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:

g u e s s n + 1 = 1 2 g u e s s n + x g u e s s n

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:

  • The function starts with an initial guess (half of the input value).
  • It iteratively refines the guess until the difference between guess² and x is within the specified tolerance.
  • If the input is negative, it raises a ValueError, similar to math.sqrt().

Use Cases and Learning Value

  • Great for understanding how numerical methods converge to solutions.
  • Helps visualize precision and convergence rates.
  • Not recommended for production unless specifically required, since built-in functions are faster and more accurate.

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.

When to Use Each Method? Find the Best Fit For Your Project

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:

  • math.sqrt() and cmath.sqrt() will raise errors on unsupported input types (e.g., negative numbers for math.sqrt()).
  • math.isqrt() returns only the integer floor of the square root—no decimals.
  • ** 0.5 is convenient but less safe for negative or complex inputs.
  • np.sqrt() is ideal in data science and scientific computing contexts due to its ability to handle large arrays efficiently.

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.

Practical Applications of Square Root Functions in Python

Subscribe to upGrad's Newsletter

Join thousands of learners who receive useful tips

Promise we won't spam!

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.

If you want to deepen your Python skills and apply them to fields like data analysis, finance, and engineering, enroll in upGrad’s DBA in Emerging Technologies with Concentration in Generative AI. Master the techniques behind intelligent, data-driven applications. Start today!

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.  

Conclusion 

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. 

Enhance Your Python Skills With upGrad!

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

Frequently Asked Questions (FAQs)

1. How to compute square roots in python in a loop without performance issues?

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.

2. Can I use square root calculations for custom scoring systems in games?

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.

3. What should I use if I need square roots in Python results rounded to the nearest whole number?

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.

4. How do I square root a column in a Pandas DataFrame?

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.

5. Can I compute square roots in Python without using built-in functions?

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.

6. What’s the best method for applying square roots in Python during real-time data processing?

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.

7. How are square roots in Python used in image processing?

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.

8. How do I apply square roots in Python conditionally?

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.

9. Can I create a reusable square root utility function?

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.

10. How can square roots in Python help in anomaly detection?

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.

11. Is it safe to apply square roots in Python to user-generated input?

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.

12. How can I compute square roots of negative numbers in Python?

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. 

13. Can I use square roots for vectorized array operations?

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. 

14. How do square roots help in calculating standard deviation in Python?

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. 

15. Are square roots used in Euclidean distance calculations for Python ML models?

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. 

16. Can I optimize repeated square root calculations in Python?

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. 

17. How are square roots applied in physics simulations using Python?

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. 

18. Can I combine square roots with other mathematical operations in Python?

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. 

19. How do I handle errors in Python square root calculations?

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. 

20. Can square roots in Python assist in financial modeling?

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. 

Pavan Vadapalli

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

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive Program in Generative AI for Leaders

76%

seats filled

View Program

Top Resources

Recommended Programs

LJMU

Liverpool John Moores University

Master of Science in Machine Learning & AI

Double Credentials

Master's Degree

18 Months

IIITB
bestseller

IIIT Bangalore

Executive Diploma in Machine Learning and AI

360° Career Support

Executive PG Program

12 Months

upGrad
new course

upGrad

Advanced Certificate Program in GenerativeAI

Generative AI curriculum

Certification

4 months