Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...