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

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

algorithm - 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.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...