In Python, the easiest way to find the square root of a number without the math module is with the built in exponentiation operator **.
sqrt_of_10 = 10**(1/2)
When working with numeric data in Python, one calculation which is valuable is finding the square root of a number.
We can find the square root of a number easily with the math module, but sometimes we don’t want to import modules to our code.
We can also use the built in ** to find exponents in Python. To find a square root with the ** operator, we just put “(1/2)” after **.
Below are some examples of how to use the Python built in ** operator to find square roots.
import math
print(4**(1/2))
print(9**(1/2))
print(13**(1/2))
print(90**(1/2))
print(2182**(1/2))
#Output:
2.0
3.0
3.605551275463989
9.486832980505138
46.71188285650665
Finding the Square Root of a Number Without the Python math Module
We can also estimate the square root of a number without the Python math module. To compute the square root in Python without the Python math module, we can employ the help of Newton’s Method.
Newton’s method is a root finding algorithm which can help us find an approximation of a function.
We can use Newton’s method to find the square root of a number in Python.
Below is a function which you can use to utilize Newton’s method to find an approximation for the square root of a number to precision level “a”. For a comparison, we will also use the sqrt() function from the Python math module.
import math
def newton_sqrt(n,a):
x = n
while(True):
root = 0.5*(x+(n/x))
if (abs(root-x) < a):
break
x = root
return root
print(math.sqrt(13))
print(newton_sqrt(13,0.1))
print(math.sqrt(50))
print(newton_sqrt(50,0.0001))
print(math.sqrt(100))
print(newton_sqrt(100,0.000001))
print(math.sqrt(313))
print(newton_sqrt(313,0.00000001))
#Output:
3.605551275463989
3.6063454894655185
7.071067811865477
7.0710678118654755
10.0
10.0
17.69180601295413
17.69180601295413
As shown above, Newton's method allows us to get a pretty good approximation of the square root of a number without using the math module.
Hopefully this article has been beneficial for you to learn how to find the square root of a number without the math module in Python.