Square root of a number is a value, which, when multiplied by itself results in the value. Square root is represented by √ symbol. Thus,
√9 = 3, since 3 * 3 = 9.
In this article, we will look at different ways to calculate square root with python.
**
operator is used to raise a number to some power. Square root of a number is the number raised to a power of 1/2.Thus,
Square root = (Number)1/2
Or
Square root = (Number)0.5
Using this formula, python program to get square root can be written as
# read number num = int(input('Enter a number: ')) sqrt = num ** 0.5 print('Square root is:', sqrt)
Output is
Enter a number: 12
Square root is: 3.4641016151377544
Method 2: Using pow() function
Python’s math module has a pow()
function which takes 2 arguments:
1. Number whose square root needs to be calculated.
2. Power to which the number should be raised.
As stated above, square root of a number can be calculated by raising it to power 1/2 or 0.5. Hence, 0.5 supplied as second argument to pow()
results in square root of number. Example,
import math num = int(input('Enter a number: ')) # raise number to power of 0.5 sqrt = math.pow(num,0.5) print('Square root is:', sqrt)
Output is
Enter a number: 25
Square root is: 5.0
isqrt()
function of math
module calculates the square root of the values supplied as argument and returns the integer or whole number part of square root. Example,
import math num = int(input('Enter a number: ')) sqrt = math.isqrt(num) print('Square root is:', sqrt)
Output of this program is
Enter a number: 27
Square root is 5
Note that the square root of 25 is 5.2(rounded off) but isqrt()
returns its integer part, that is, 5.
Square root of complex numbers
Complex numbers are represented as x + yj
where,
x and y are real numbers and j is imaginary unit.
It is possible to find the square root of a complex number using sqrt()
function of python’s cmath
module.
sqrt()
accepts a complex number as argument and returns its square root.
Real and imaginary parts of the square root can be accessed using real
and imag
fields of this square root respectively.
Example program is given below
import cmath # define a complex number num = 5 + 4j # find its square root sqrt = cmath.sqrt(num) print('Square root is {0:0.2f} + {1:0.2f}j'.format(sqrt.real,sqrt.imag))
This prints
Square root is 2.39 + 0.84j
Square root values are formatted to 2 decimal places.