Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
463 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...