Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Python 

Heron's Algorithm - Square Roots by Hand

So, I'm dabbling in to Python a bit more and my professor mentioned something about Heron's Algorithm. I thought it was interesting so I made a little concept based on his psuedo-code.

This basically will keep iterating until it finds the perfect square root of the number you input. It starts off by taking dividing the root by your guess, adding your guess to that, and then dividing that whole thing by two, to find the average. It then creates that as your new guess and the whole process keeps going.

See below:

Code
intSquare = int(input("Please enter the square root find the answer of: "))
intGuess = float(input("Please enter the square root guess: "))

intApprox = abs((intGuess + intSquare/intGuess)/2.)
resFound = False
numTry = 0
while not resFound:
    numTry += 1
    prevApprox = intApprox
    print("Guess number " + str(numTry) + " is " + str(intApprox))
    intApprox = 1/2 * (intApprox + intSquare/intApprox)
    if (intApprox - prevApprox) == 0:
            resFound = True
print("Using only " + str(numTry) + " iterations, the actual square root was found to be " + str(intApprox))

Running this, we get something like this:

[Image: tR3T.png]
Nice program. I remember writing something similar previously oh & nice code.

fun method
If you always do what you’ve always done, you’ll always get what you’ve always got.
you should use abs(intApprox-prevApprov) <= EPS
where EPS is some small value such as 1e-6 that is a tolerable value of error.
,.
(Sep 8, 2017 09:40 AM)Ronnie Coleman Wrote:  you should use abs(intApprox-prevApprov) <= EPS
where EPS is some small value such as 1e-6 that is a tolerable value of error.

https://docs.python.org/3/library/math.h...th.isclose

Does what you're describing.


Possibly Related Threads...
Thread / Author Replies Views Last Post
[Java] by ComputroniumApr 11, 2018 09:48 AM 3 209 Apr 11, 2018 09:48 AM
Last Post: Computronium
[C] by GetWAug 23, 2017 12:18 AM 0 164 Aug 23, 2017 12:18 AM
Last Post: GetW
[Shell] by TravelersAug 11, 2017 07:04 PM 0 81 Aug 11, 2017 07:04 PM
Last Post: Travelers