0

I've created an algorithm on python to find the approximate square root of a number but I'm interested to see if there are any shortcuts I can make. I have a while loop that needs to call back to a statement before the loop. For example, it starts at 2, goes to 6, then loops back to 1, up to 6, back to 1, etc. I tried using an i variable that works but not to sure if its the most efficient. So essentially can anyone help me in terms of making this algorithm more efficient, thanks.

def rooter(A , R):
i = 0
if A <= 0:
    print("Invalid number")
    return -1
(c) = (A / R)
while abs(R - c) > 0.01:
    if i > 1:
        (c) = (A / R)
    s = (1/2) * (R + c)
    R = s
    i +=1
answer = (round(R, 3))
print(answer)

rooter(4, 100)

R represents the accuracy of the calculation.

Andyw3
  • 90
  • 1
  • 5
  • see [How to get a square root for 32 bit input in one clock cycle only?](https://stackoverflow.com/a/34657972/2521214) its mine binary search based `sqrt` that does not use multiplication ... its has more iterations than your approximation but with much simpler and faster iteration code ... also in floating point you can do `sqrt(x) = exp10(log10(x/2))` the base of exp,log can be any ... – Spektre Nov 24 '19 at 08:17

1 Answers1

0

You can simplify your code by simulating a do ... while

while True:
    c = A / R
    R = (R + c)/2
    if abs(R - c) < 0.01: break

Note that the accuracy of the calculation is 0.01, not R as you stated.

Damien
  • 4,809
  • 4
  • 15
  • 20