简体   繁体   中英

square root without pre-defined function in python

How can one find the square root of a number without using any pre-defined functions in python?

I need the main logic of how a square root of a program works. In general math we will do it using HCF but in programing, I am not able to find the logic.

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.

def squareRoot(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 .

This worked for me:

def sqrt(n):
    for i in range(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.

here is the way you can get square root without using any inbuilt function of python.

def findSqrt(n):
    sqrtNum = n / 2
    temp = 0

    while sqrtNum != temp:
        temp = sqrtNum
        sqrtNum = (n / temp + temp) / 2

    return sqrtNum

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.

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=1
for i in range(accuracy+1):
    while (s+step)**2<=a:
        s+=step
    step=step/10
s=format(s,'.'+str(accuracy)+'f')
print(s)

square root without pre-defined function in python

a=eval(input("Enter a number to see the squareroot:"))
b=0
x=(1+a/1)/2
while b!=10:
    b+=1
    x=(x+a/x)/2
print(x)

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 = 0
    while (y != z):
        z = y
        y = ( y + n/y) / 2
    return math.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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM