I am not sure of exactly what you are trying to achieve, but if I correctly understand, the following code should address what you are looking for:
Solution
import numpy as np # need this to test the custom
# defined function SQRT()
# against numpy's sqrt() function.
# err_epsilon = the acceptable error for stopping the loop.
def SQRT(n, err_epsilon = 1e-8):
fg = n/2
fG = fg + 1
while abs(fg-fG)>err_epsilon:
fg = fG
fG = (0.5) * (fG + (n/fG))
return 0.5*(fG+fg)
# Test against numpy.sqrt()
SQRT(2), np.sqrt(2)
Result:
Note that we had err_epsilon=1e-8
and so should have correct square-root calculated up to 8 places after the decimal. And the following results conform to that: 1.41421356
. In fact they are the same up to the 11-th place after the decimal.
(1.4142135623738925, 1.4142135623730951)
An Option
Since, you prefer avoiding a while and/or conditionals
, you may consider using the following. But, you can not possibly stop the loop without a conditional step that evaluates when to stop calculations. The implementation given above makes use of the conditional and a while (as you do not know a priori how many loops it would take to get to the accepted level of error-threshold.
You are actually not using the variable i
in the for
loop. And hence, it is best to discard its value, should you decide to use the for
loop with the range
function.
def fun(n, start = 0, stop = 10, step = 1):
fG = n/2
# we skip saving the variable generated
# from the range iterator.
for _ in range(start,stop,step):
fG = (0.5) * (fG + (n/fG))
return fG
Square-root Algorithm
Assuming you are trying to find square-root, I would encourage you to take a look at these:
- Square Root with Babylonian Algorithm: Python Implementation [1]
- Writing your own square root function
- Finding the square root using Newton's method (errors!). Important.
- Python Implementation of Square Root with Newton's Method
- Newton Square Root Method in Python
Quoting [1] as-is
:
def BabylonianAlgorithm(number):
if(number == 0):
return 0;
g = number/2.0;
g2 = g + 1;
while(g != g2):
n = number/ g;
g2 = g;
g = (g + n)/2;
return g;
print('The Square root of 0.3 =', BabylonianAlgorithm(0.3));