Returns the square root using the BisectionMethod. DefsqrtBI (x, epsilon): assertx & amp; gt; 0, Xmustbenon-nagtive, not + str .. use the Bisection Method to obtain the square root.
def sqrtBI(x, epsilon): assert x>0, 'X must be non-nagtive, not ' + str(x) assert epsilon > 0, 'epsilon must be postive, not ' + str(epsilon) low = 0 high = x guess = (low + high)/2.0 counter = 1 while (abs(guess ** 2 - x) > epsilon) and (counter <= 100): if guess ** 2 < x: low = guess else : high = guess guess = (low + high)/2.0 counter += 1 return guess
Verify it.
>>> SqrtBI (2, 0.000001)
>>> 1.41421365738
The above method, if X <1, will have a problem. Because the square root of X (X <1) is not in the range of [0, x. For example, 0.25, the square root of which -- 0.5 is not in the range of [0, 0.25.
>>> SqrtBI (0.25, 0.000001)
>>> 0.25
Then how can we obtain the square root of 0.25?
You only need to slightly modify the above code. Pay attention to the code of lines 6 and 7.
def sqrtBI(x, epsilon): assert x>0, 'X must be non-nagtive, not ' + str(x) assert epsilon > 0, 'epsilon must be postive, not ' + str(epsilon) low = 0 high = max(x, 1.0) ## high = x guess = (low + high)/2.0 counter = 1 while (abs(guess ** 2 - x) > epsilon) and (counter <= 100): if guess ** 2 < x: low = guess else : high = guess guess = (low + high)/2.0 counter += 1 return guess
Verify:
>>> SqrtBI (0.25, 0.000001)
>>> 0.5