3 ms·
https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Bakhshali_method https://en.wikipedia.org/wiki/Methods_of_computing_square_ro... python impleme
by photochemsyn 3y ago
https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Bakhshali_method https://en.wikipedia.org/wiki/Methods_of_computing_square_ro...
python implementation (for numbers >= 2)
def bakshali(S, iters=5, a=0, b=0):
x = S//2
print(f'inital approximation = {x}')
for n in range(iters):
a = (S - x**2) / (2*x)
b = x + a
print(f'{x}')
x = b - (a**2)/(2*b)
return x
Converges pretty fast!
- tasty_freeze 3y agoIs this common in python to declare local variables as fake parameters? The downside is obvious: it clutters the function interface with red herrings. What is the upside?
- 1024core 3y agoThe upside is that if you wanted a different "iter", "a" or "b", you could just specify it in the arguments.
- tasty_freeze 3y agoThe iter part I get, but I don't see how the caller can affect a or b. Whatever value supplied for a or b will be replaced by values in dependent of a and b during the loop. a is a function of S and x (which initially is a function of S) and b is a function of x and the just revised value for a.
- photochemsyn 3y agoNo, it was just to shorten the code block length for the comment section (for a and b, iters makes more sense as one might want to allow the caller to change that) :)