Option 1: math.sqrt()

The math module from the standard library has a sqrt function to calculate the square root of a number. It takes any type that can be converted to float (which includes int) and returns a float.

>>> import math
>>> math.sqrt(9)
3.0

Option 2: Fractional exponent

The power operator (**) or the built-in pow() function can also be used to calculate a square root. Mathematically speaking, the square root of a equals a to the power of 1/2.

The power operator requires numeric types and matches the conversion rules for binary arithmetic operators, so in this case it will return either a float or a complex number.

>>> 9 ** (1/2)
3.0
>>> 9 ** .5  # Same thing
3.0
>>> 2 ** .5
1.4142135623730951

(Note: in Python 2, 1/2 is truncated to 0, so you have to force floating point arithmetic with 1.0/2 or similar. See Why does Python give the "wrong" answer for square root?)

This method can be generalized to nth root, though fractions that can't be exactly represented as a float (like 1/3 or any denominator that's not a power of 2) may cause some inaccuracy:

>>> 8 ** (1/3)
2.0
>>> 125 ** (1/3)
4.999999999999999

Edge cases

Negative and complex

Exponentiation works with negative numbers and complex numbers, though the results have some slight inaccuracy:

>>> (-25) ** .5  # Should be 5j
(3.061616997868383e-16+5j)
>>> 8j ** .5  # Should be 2+2j
(2.0000000000000004+2j)

(Note: the parentheses are required on -25, otherwise it's parsed as -(25**.5) because exponentiation is more tightly binding than negation.)

Meanwhile, math is only built for floats, so for x<0, math.sqrt(x) will raise ValueError: math domain error and for complex x, it'll raise TypeError: can't convert complex to float. Instead, you can use cmath.sqrt(x), which is more accurate than exponentiation (and will likely be faster too):

>>> import cmath
>>> cmath.sqrt(-25)
5j
>>> cmath.sqrt(8j)
(2+2j)

Precision

Both options involve an implicit conversion to float, so floating point precision is a factor. For example let's try a big number:

>>> n = 10**30
>>> x = n**2
>>> root = x**.5
>>> root == n
False
>>> root - n  # how far off are they?
0.0
>>> int(root) - n  # how far off is the float from the int?
19884624838656

Very large numbers might not even fit in a float and you'll get OverflowError: int too large to convert to float. See Python sqrt limit for very large numbers?

Other types

Let's look at Decimal for example:

Exponentiation fails unless the exponent is also Decimal:

>>> decimal.Decimal('9') ** .5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ** or pow(): 'decimal.Decimal' and 'float'
>>> decimal.Decimal('9') ** decimal.Decimal('.5')
Decimal('3.000000000000000000000000000')

Meanwhile, math and cmath will silently convert their arguments to float and complex respectively, which could mean loss of precision.

decimal also has its own .sqrt(). See also calculating n-th roots using Python 3's decimal module

🌐
Real Python
realpython.com › python-square-root-function
The Python Square Root Function – Real Python
November 3, 2024 - The Python square root function, sqrt(), is part of the math module and is used to calculate the square root of a given number. To use it, you import the math module and call math.sqrt() with a non-negative number as an argument.
🌐
Enki
enki.com › post › how-to-square-numbers-in-python-sqrt
Enki | Blog - How to Square Numbers in Python - sqrt
This approach might be more familiar ... when you need to reverse a squaring operation. In Python, you can easily calculate square roots using the math.sqrt() function:...
Top answer
1 of 11
107

Option 1: math.sqrt()

The math module from the standard library has a sqrt function to calculate the square root of a number. It takes any type that can be converted to float (which includes int) and returns a float.

>>> import math
>>> math.sqrt(9)
3.0

Option 2: Fractional exponent

The power operator (**) or the built-in pow() function can also be used to calculate a square root. Mathematically speaking, the square root of a equals a to the power of 1/2.

The power operator requires numeric types and matches the conversion rules for binary arithmetic operators, so in this case it will return either a float or a complex number.

>>> 9 ** (1/2)
3.0
>>> 9 ** .5  # Same thing
3.0
>>> 2 ** .5
1.4142135623730951

(Note: in Python 2, 1/2 is truncated to 0, so you have to force floating point arithmetic with 1.0/2 or similar. See Why does Python give the "wrong" answer for square root?)

This method can be generalized to nth root, though fractions that can't be exactly represented as a float (like 1/3 or any denominator that's not a power of 2) may cause some inaccuracy:

>>> 8 ** (1/3)
2.0
>>> 125 ** (1/3)
4.999999999999999

Edge cases

Negative and complex

Exponentiation works with negative numbers and complex numbers, though the results have some slight inaccuracy:

>>> (-25) ** .5  # Should be 5j
(3.061616997868383e-16+5j)
>>> 8j ** .5  # Should be 2+2j
(2.0000000000000004+2j)

(Note: the parentheses are required on -25, otherwise it's parsed as -(25**.5) because exponentiation is more tightly binding than negation.)

Meanwhile, math is only built for floats, so for x<0, math.sqrt(x) will raise ValueError: math domain error and for complex x, it'll raise TypeError: can't convert complex to float. Instead, you can use cmath.sqrt(x), which is more accurate than exponentiation (and will likely be faster too):

>>> import cmath
>>> cmath.sqrt(-25)
5j
>>> cmath.sqrt(8j)
(2+2j)

Precision

Both options involve an implicit conversion to float, so floating point precision is a factor. For example let's try a big number:

>>> n = 10**30
>>> x = n**2
>>> root = x**.5
>>> root == n
False
>>> root - n  # how far off are they?
0.0
>>> int(root) - n  # how far off is the float from the int?
19884624838656

Very large numbers might not even fit in a float and you'll get OverflowError: int too large to convert to float. See Python sqrt limit for very large numbers?

Other types

Let's look at Decimal for example:

Exponentiation fails unless the exponent is also Decimal:

>>> decimal.Decimal('9') ** .5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ** or pow(): 'decimal.Decimal' and 'float'
>>> decimal.Decimal('9') ** decimal.Decimal('.5')
Decimal('3.000000000000000000000000000')

Meanwhile, math and cmath will silently convert their arguments to float and complex respectively, which could mean loss of precision.

decimal also has its own .sqrt(). See also calculating n-th roots using Python 3's decimal module

2 of 11
25

SymPy

Depending on your goal, it might be a good idea to delay the calculation of square roots for as long as possible. SymPy might help.

SymPy is a Python library for symbolic mathematics.

import sympy
sympy.sqrt(2)
# => sqrt(2)

This doesn't seem very useful at first.

But sympy can give more information than floats or Decimals:

sympy.sqrt(8) / sympy.sqrt(27)
# => 2*sqrt(6)/9

Also, no precision is lost. (√2)² is still an integer:

s = sympy.sqrt(2)
s**2
# => 2
type(s**2)
#=> <class 'sympy.core.numbers.Integer'>

In comparison, floats and Decimals would return a number which is very close to 2 but not equal to 2:

(2**0.5)**2
# => 2.0000000000000004

from decimal import Decimal
(Decimal('2')**Decimal('0.5'))**Decimal('2')
# => Decimal('1.999999999999999999999999999')

Sympy also understands more complex examples like the Gaussian integral:

from sympy import Symbol, integrate, pi, sqrt, exp, oo
x = Symbol('x')
integrate(exp(-x**2), (x, -oo, oo))
# => sqrt(pi)
integrate(exp(-x**2), (x, -oo, oo)) == sqrt(pi)
# => True

Finally, if a decimal representation is desired, it's possible to ask for more digits than will ever be needed:

sympy.N(sympy.sqrt(2), 1_000_000)
# => 1.4142135623730950488016...........2044193016904841204
🌐
TradingCode
tradingcode.net › python › math › square-root
How to calculate the square root in Python? • TradingCode
For that we call Python’s print() function several times. Here’s what that displays: √16 = 4.0 √81 = 9.0 √8301.43 = 91.11218359802382 √98.25 = 9.912113800799505 ... A square root is like asking ourselves, “what value can we multiply by itself to get this outcome?”. That multiplication by itself is also called squaring.
🌐
W3Schools
w3schools.com › python › ref_math_sqrt.asp
Python math.sqrt() Method
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... # Import math Library import math # Return the square root of different numbers print (math.sqrt(9)) print (math.sqrt(25)) print (math.sqrt(16)) Try it Yourself »
🌐
Programiz
programiz.com › python-programming › examples › square-root
Python Program to Find the Square Root
# Python Program to calculate the square root # Note: change this value for a different result num = 8 # To take the input from the user #num = float(input('Enter a number: ')) num_sqrt = num ** 0.5 print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
🌐
LearnDataSci
learndatasci.com › solutions › python-square-root
Python Square Root: Real and Complex – LearnDataSci
To get square root, you need to use 0.5 as your second operand, as shown in the introduction. The following snippet shows another example of how we can use **0.5 to calculate the square root for a range of values:
Find elsewhere
🌐
Career Karma
careerkarma.com › blog › python › python sqrt(): a how-to guide
Python sqrt(): A How-To Guide
July 20, 2022 - You can get the square root of a number by raising it to a power of 0.5 using Python’s exponent operator (**) or the pow() function. ... When you work with multiple numbers requiring square roots, you will find that using the sqrt() function is ...
🌐
Analytics Vidhya
analyticsvidhya.com › home › python square root
Python Square Root
October 10, 2024 - Learn how to compute square roots using Python’s built-in math module. Discover alternative ways to find square roots using external libraries like numpy. Be able to handle edge cases such as negative numbers. Implement square root calculations in real-world examples. ... A square root of a number is a value that, when multiplied by itself, results in the original number.
🌐
Tutorialspoint
tutorialspoint.com › home › python › python square root function
Python Square Root Function
February 21, 2009 - The Python math.sqrt() method is used retrieve the square root of the given value. The square root of a number is the factor of multiplying the number by itself to get that number.
Top answer
1 of 14
114

Note: There is now math.isqrt in stdlib, available since Python 3.8.

Newton's method works perfectly well on integers:

def isqrt(n):
    x = n
    y = (x + 1) // 2
    while y < x:
        x = y
        y = (x + n // x) // 2
    return x

This returns the largest integer x for which x * x does not exceed n. If you want to check if the result is exactly the square root, simply perform the multiplication to check if n is a perfect square.

I discuss this algorithm, and three other algorithms for calculating square roots, at my blog.

2 of 14
48

Update: Python 3.8 has a math.isqrt function in the standard library!

I benchmarked every (correct) function here on both small (0…222) and large (250001) inputs. The clear winners in both cases are gmpy2.isqrt suggested by mathmandan in first place, followed by Python 3.8’s math.isqrt in second, followed by the ActiveState recipe linked by NPE in third. The ActiveState recipe has a bunch of divisions that can be replaced by shifts, which makes it a bit faster (but still behind the native functions):

def isqrt(n):
    if n > 0:
        x = 1 << (n.bit_length() + 1 >> 1)
        while True:
            y = (x + n // x) >> 1
            if y >= x:
                return x
            x = y
    elif n == 0:
        return 0
    else:
        raise ValueError("square root not defined for negative numbers")

Benchmark results:

  • gmpy2.isqrt() (mathmandan): 0.08 µs small, 0.07 ms large
  • int(gmpy2.isqrt())*: 0.3 µs small, 0.07 ms large
  • Python 3.8 math.isqrt: 0.13 µs small, 0.9 ms large
  • ActiveState (optimized as above): 0.6 µs small, 17.0 ms large
  • ActiveState (NPE): 1.0 µs small, 17.3 ms large
  • castlebravo long-hand: 4 µs small, 80 ms large
  • mathmandan improved: 2.7 µs small, 120 ms large
  • martineau (with this correction): 2.3 µs small, 140 ms large
  • nibot: 8 µs small, 1000 ms large
  • mathmandan: 1.8 µs small, 2200 ms large
  • castlebravo Newton’s method: 1.5 µs small, 19000 ms large
  • user448810: 1.4 µs small, 20000 ms large

(* Since gmpy2.isqrt returns a gmpy2.mpz object, which behaves mostly but not exactly like an int, you may need to convert it back to an int for some uses.)

🌐
Plain English
plainenglish.io › blog › 6-amazing-algorithms-to-get-the-square-root-and-any-root-of-any-number-in-python-3c976ad1ca04
6 Amazing Algorithms to Get the Square Root (and Any Root) of any Number in Python
That is why in some algorithms we will only calculate the square root. To test our algorithms, we will find sqrt(531610), which truncated to the first 10 decimals is 729.1159029948. Also, the number of iterations of all algorithms will be the same: 10 iterations. This is the most straightforward method. It can be interpreted as the brute-force method for obtaining the roots.
🌐
Codedamn
codedamn.com › news › python
How to calculate square root in Python (with examples)
March 18, 2024 - For example, the square root of 9 is 3, because 3 multiplied by 3 equals 9.
🌐
Python Guides
pythonguides.com › square-root-in-python
Square Root In Python
November 21, 2024 - Here is the syntax of the sqrt() function in Python. ... The math.sqrt() function takes a single argument x and returns the square root of x.
🌐
Initial Commit
initialcommit.com › blog › python-square-root
Python Square Root
The standard square root function requires a real number as an argument: >>> math.sqrt([4,9,16,25]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: must be real number, not list · NumPy, on the other hand, works with arrays and can therefore handle multiple inputs at once - for example, in the form of a list:
🌐
Altcademy
altcademy.com › blog › how-to-do-square-root-in-python
How to do square root in Python
June 13, 2023 - Calculate the next guess x1 using the formula: x1 = (x0 + number/x0) / 2. Repeat step 2 using the new guess x1 until the difference between the current guess and the previous guess is smaller than a specified tolerance value.
🌐
Real Python
realpython.com › videos › intro-square-roots-math-python
An Introduction to Square Roots in Math and in Python (Video) – Real Python
03:28 In addition to the sqrt() function, Python 3.8 introduced the isqrt() function in the math module. Now that I’ve imported it, let me run it on 25. 03:39 No problem here. Still in perfect square land.
Published   July 13, 2021
🌐
Python
docs.python.org › 3 › library › math.html
math — Mathematical functions
Return the square root of x. ... Return the Euclidean distance between two points p and q, each given as a sequence (or iterable) of coordinates. The two points must have the same dimension. ... Added in version 3.8. ... Return an accurate floating-point sum of values in the iterable. Avoids loss of precision by tracking multiple intermediate partial sums.