Square Root Without Pre-defined Function In Python
Solution 1:
There is a famous mathematical method called Newton–Raphson method for finding successively better approximations to the roots.
Basically , this method takes initial value and then in successful iterations converges to the solution.You can read more about it here.
Sample code is attached here for your reference.
defsquareRoot(n):
x=n
y=1.000000#iteration initialisation.
e=0.000001#accuracy after decimal place.while x-y > e:
x=(x+y)/2
y=n/x
print x
n = input('enter the number : ')
squareRoot(n)
Here you can increase the accuracy of square root result by adding '0' digits in e and y after decimal place.
Also there are other methods like binary search for finding square roots like shown here.
Solution 2:
This worked for me:
defsqrt(n):
for i inrange(1, n+1):
if (n % i == 0) and (i * i == n):
return i
break
Basically the program run for loop from 1 to n, then check if n % i = 0 and i squared = n, if true - return i and break.
Solution 3:
I would approach this by building an algorithm that gives a precise guess because these steps are easy to understand and can be repeated until very accurate. For example:
- Build in the known perfect squares (2^2 is 4, 4^2 is 16, etc.)
- Find which perfect squares the given number lies between (if given 10, it lies between 3^2 (9) and 4^2 (16)). Therefore, the square root of 10 is somewhere between 3 and 4.
Check out this link for an easy explanation of this algorithm and how to repeat to ensure accuracy.
Solution 4:
Here is a way you can do it. Note that it is not the most mathematically efficient way it is just an easy way to do it without messing with weird mathematics:
a=int(input('number! '))
accuracy=10#number of decimals
s=0
step=1for i inrange(accuracy+1):
while (s+step)**2<=a:
s+=step
step=step/10
s=format(s,'.'+str(accuracy)+'f')
print(s)
Solution 5:
The following python implementation is based on C++ implementation. The code does not directly use sqrt but uses math.frexp
and math.ldexp
to calculate the sqrt. This algorithms are like any other is good for training. It is better to use math.sqrt
in professional settings since the function uses direct Intel instruction or ARM64 instruction.
import math
def sqrt(n):
if n < 0:
raise ArithmeticError()
n, exp = math.frexp(n)
if (exp & 1):
exp -= 1
n *= 2
y = (1 + n) / 2
z = 0while (y != z):
z = y
y = ( y + n/y) / 2returnmath.ldexp(y, int(exp/2))
import unittest
class TestSqrt(unittest.TestCase):
def test_simple(self):
self.assertEqual(sqrt(4), math.sqrt(4))
def test_various(self):
l = [4, 9, 64, 49, 39499, 48484]
for i in l:
self.assertEqual(sqrt(i), math.sqrt(i))
if __name__ == '__main__':
unittest.main()
Post a Comment for "Square Root Without Pre-defined Function In Python"