How to calculate the square root in Python

Posted in Python by Dirk - last update: Feb 15, 2024

In mathematics, the square root of a number is a value that, when multiplied by itself, gives the original number. It is denoted by the radical symbol (√) or by using the exponent 0.5. For example, the square root of 9 is 3 because 3 * 3 = 9. In Python, you can calculate square roots of a positive number using the sqrt function from the math module or by using the exponent operator (**). If you want to calculate the square root for complex numbers you can use the cmath.sqrt() fucntion from the cmath module.

Square root of positive numbers

import math

# Using math.sqrt
positive_number = 9
result = math.sqrt(positive_number)
print(f"Square root of {positive_number} is {result}")

# Using exponent operator
result_exponent = positive_number ** 0.5
print(f"Square root of {positive_number} using exponent is {result_exponent}")

Output:

Square root of 9 is 3.0
Square root of 9 using exponent is 3.0

Note: the result of the operation is always float even if you start with integers and the result could be integer.

Sqare root of negative numbers

For the square root of a negative number, Python’s math.sqrt function will raise a ValueError because square roots of negative numbers are not defined in the real number system.

Example

import math

# Using math.sqrt
negative_number = -9
result = math.sqrt(negative_number)
print(f"Square root of {negative_number} is {result}")

This will raise ValueError: math domain error

However, you can work with complex numbers using the cmath module:

import cmath

negative_number = -9
result_complex = cmath.sqrt(negative_number)
print(f"Square root of {negative_number} (as a complex number) is {result_complex}")

Output:

Square root of -9 (as a complex number) is 3j

The type of result_complex is complex.

Other articles