Hack Forums
[Python] Heron's Algorithm - Square Roots by Hand - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [Python] Heron's Algorithm - Square Roots by Hand (/showthread.php?tid=5712161)



Heron's Algorithm - Square Roots by Hand - SIM-2306826 - Sep 6, 2017

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]


* - Lucifer's Inferno - Sep 6, 2017

Nice program. I remember writing something similar previously oh & nice code.

fun method


* - Ronnie Coleman - Sep 8, 2017

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

(Sep 8, 2017 09:40 AM)_Russ 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.html#math.isclose

Does what you're describing.