How do I Calculate Square Root in Python?

The square root is a mathematical concept where you get a numeric value that, when mathematically computed by itself using multiplication, returns the original real number. When designing an application like a calculator or performing some mathematical operation, there is a need to accurately compute the square root operation. In such cases, python gives flexibility to utilize the standard built-in function and modules to calculate square root. 

This article will demonstrate the approaches to calculating square roots in Python. 

How to Calculate Square Root in Python?

The square root in Python is basically about extracting the root value of the real number. To compute the square root in Python, the standard cmath, math module, and built-in libraries are used. For demonstration, follow the below set of approaches:

  1. Approach 1: Compute the Square Root Using Double Star “**” Operator
  2. Approach 2: Computing the Square Root Using the “pow()” function
  3. Approach 3: Compute Square Root Using the “sqrt()” Function
  4. Approach 4: Computing Square Root of Complex Number (a+ib)
  5. Approach 5: Extracting Absolute Value from Complex Number Square Root 
  6. Approach 6: Calculate the Square Root of Integer Numbers
  7. Approach 7: Calculate the Square Root through List Comprehension
  8. Approach 8: Calculate the Square Root through Looping
  9. Approach 9: Compute the Square Root of List Items through Enumerate
  10. Approach 10: Calculate the Square Root Using the sympy module
  11. Approach 11: Calculate the Square Root Using the Numpy Library

Approach 1: Compute the Square Root Using Double Star “**” Operator 

The double star or two-asterisk operator, also known as the “exponentiation operator”, can be utilized to compute the square root in Python. To calculate square root use the root “” numeric value “0.5” as the second operand of the “**” operator. Here’s how you can perform these operations on real or imaginary numbers:

# Positive and negative values
num_pos = 20
num_neg = -20
# square roots the list items through enumerate
sq_pos= num_pos**0.5
sq_neg= num_neg**0.5

print("\n Square root of positive 20:\n\n", "√", "20", "=", sq_pos)
print("\n Square root of negative 20:\n\n", "√", "-20", "=", sq_neg)

In the above code, the square root for positive and negative “20” is calculated using the “**” operator.

Output

To get the only positive or real number, use the “**” operator with the “abs()” function as shown in the following snippet:

# negative values
num_neg = -20
#using operator 
sq_neg=  abs(num_neg) **0.5

print("\n Square root of negative 20:\n\n", "√", "-20", "=", sq_neg)

Output

Approach 2: Computing the Square Root Using the “pow()” Function

To compute the root square in Python, use the “pow()” function. To do so, specify the real number with the numeric “” value (0.5) and separate the pow() arguments using the commas (,). To get the only positive or real number, utilize the “abs()” function within the “pow()” function. Here’s how you can compute the square root in Python using the pow() function: 

# Positive and negative values
num_pos = 25
num_neg = -25
# square roots the list items through enumerate
sq_pos= pow(num_pos, 0.5)
sq_neg= pow(num_neg, 0.5)
sq_neg1=  pow(abs(num_neg), 0.5)

print("\n Square root of positive 25:\n\n", "√", "25", "=", sq_pos)
print("\n Square root of negative 25:\n\n", "√", "-25", "=", sq_neg)
print("\n Square root of negative 25:\n\n", "√", "-25", "=", sq_neg1)

Output

Approach 3: Compute Square Root Using the “sqrt()” Function

To calculate the square root in Python, use the standard built-in locally installed package of the “math” module. For instance, the “sqrt()” function is used to compute the root square in Python. However, the “math” module applies to the non-negative real number. To operate on the non-positive number utilize the “cmath” module otherwise the program returns the ValueError;

ValueError: math domain error

Here’s how you can perform the square root operation on the number:

# Import the math module to perform a mathematical operation
import math 

print("square root of 8:", math.sqrt(8), "\n") 

# print the error when the number<0 
print("square root of non-positive number:\n") 
print(math.sqrt(-1)) 

Output

Approach 4: Computing Square Root of Complex Number (a+ib)

To compute the square root of the complex number (a+bi) in Python, import the “cmath” module. To do so, use the “sqrt()” function with the “cmath” module using the dot(.) operator. To print the output, the f-string literal is used. The “0”, “1”, and “2” is the index position of the argument to be formatted as the results of the operation performed in the “format()” function:

# Import the cmath module to perform a mathematical operation to compute real or complex numbers
import cmath

real_complex_num = 1+8j

c_sqrt = cmath.sqrt(real_complex_num)

#f-string to format string
print('\nThe square root of complex number "{0}" is: {1:0.3f}+{2:0.3f}j'
      .format(real_complex_num ,c_sqrt.real,c_sqrt.imag))

The “.3f” is a format specifier depicting the three decimal places of floating point numbers shown in the output for real and complex numbers.

Output 

Approach 5: Extracting Absolute Value From Complex Number Square Root 

To calculate the absolute value of the square root in Python, use the built-in “abs()” function along with the “math.sqrt()” function. Here’s how you can compute the absolute square root of a complex number in Python: 

#import the "math" module
import math

#extract the "absolute" value of the number non-positive number
abs_number = math.sqrt(abs(-9))
print("Get the absolute value of the non-positive number:\n\n", 
      "√", abs(-9), " = ", abs_number)

Output

Approach 6: Calculate the Square Root of Integer Numbers

To compute the integer square root of a non-negative real number in Python, use the “isqrt()” function. The “isqrt” function will return the integer whose square is equal or less to the particular numeric value. 

Here’s how you can compute the integer square root of any non-negative real number: 

#import the "math" module
import math

#compute the square root of a non-negative integer number
sq_number = math.isqrt(123)
print("square root of the non-negative integer number:\n\n", 
      "√", '123', " = ", sq_number)

Output

The calculation for extracting the absolute value of a non-positive integer number.

To calculate the absolute value of a negative integer number, utilize the “abs()” function aggregation with the “isqrt()” function. Here’s how you can perform the square root operation on a negative integer value:

#import the "math" module
import math

#compute the square root of non-positive integer number
sq_number = math.isqrt(abs(-123))
print("\nsquare root of the non-positive integer number:\n\n", 
      "√", abs(-123), " = ", sq_number)

Output

Approach 7: Calculate the Square Root Through List Comprehension

Python gives flexible access to calculate the square root of each element in a list by utilizing list comprehension. The for…in structure iterates over each element in the list and performs the square root operation on each real number. To handle the non-positive numbers the “abs()” function is utilized. Here’s how you can compute the square root in Python on List: 

import math

# Positive and negative values
num = [-15, 20, 25.30, -20, 35]

# square roots the list items
squ_root = [math.sqrt(abs(i)) for i in num]

print("\nOriginal List:\n\n", num)
print("\nModified List:\n\n", squ_root)

Output

Approach 8: Calculate the Square Root Through Looping

To calculate square root in Python, utilize the for loop behavior. The “for” loop will iterate over the list items one by one and apply the “sqrt()” function on it, then save them in the “empty” list.  Here’s how you can perform the square root operation on the list through looping: 

import math

# Positive and negative values
num = [15, 20, 25, 30, 20, 35]

list_sq=[]
# Square roots the list items through Looping, and rounded to 2 decimals
for i in num:
    list_sq.append(round(math.sqrt(i), 2))
 
print("\nOriginal List:\n\n", num)
print("\nModified List:\n\n", list_sq)

Output

Approach 9: Compute the Square Root of List Items Through Enumerate

The enumerate function is used to iterate over the iterable (like a list). The enumerate function will iterate over the list elements with the indices value. For this purpose, the index of elements in the list is accessed by the “index” and elements are through the “i”. The square root of the element is performed by the “sqrt()” function which accesses the elements index-wise and updates the original list. 

Here’s how you can perform the enumerate operation to compute the square root of list items in Python:

import math

# Positive and negative values
num = [15, 20, 25, 30, 20, 35]

list_sq=[]

# square roots the list items through enumerate
for index, i in enumerate(num):
    num[index] = math.sqrt(i)
 
print("\n List:\n\n", num)

Output

Approach 10: Calculate the Square Root Using the sympy Module

The “sympy” module is normally used in symbolic mathematical operations. The “sympy.N” function is used to present the floating point of the number. The second argument specifies the decimal place to round the floating value of the number. Here’s how you can implement the “sympy” module to compute the square root of a number:

num=25
#import sympy module
import sympy
x=sympy.N(sympy.sqrt(num), 3)
print (f'\n square root using sympy, √ {num} =', x)

Output

Approach 11: Calculate the Square Root Using the Numpy Library

Numpy is a versatile library for handling computationally expensive mathematical problems. To compute the root square in Python, use the numpy library with the “sqrt()” function using the dot(.) notation. Here’s how you can perform the square root operation: 

#Consider importing “numpy” library
import numpy as np

# use sqrt() function with numpy library
sq= np.sqrt(25)

print("\n Square root of positive 25:\n\n", "√", "25", "=", sq)

Output

Alternatively, use the “emath” module to compute the square root in Python. 

#Consider importing the “numpy” library
import numpy as np

# Construct an 1D  array
a =np.emath.sqrt(25)

print(f'\nSquare root of √ {25} =', a)

Output 

That is all about calculating square roots in Python.  

Conclusion

To calculate the square root in Python, use the sqrt() function with the “math” module. To compute the square root of the negative or complex number utilize the “cmath” module. Alternatively, you can use the “isqrt()”, “pow()” function, and “**” operator to compute the square root. This article has demonstrated prevalent approaches to computing the square roots in Python.