can anyone help me run this code properly? when i test it, the code spits out obserd awnsers such as sqrtbi(9, 0.0001) = 2.25... instead of 3, how can i count on it to find the square root of any given number?
def sqrtbi(x, z): assert x>=0, 'x must be non-negitive, not' + str(x) assert z > 0, 'espilon must be positive, not' + str(z) low = 0 high = max(x, 1.0) guess = (low + high)/2.0 ctr = 1 while abs(guess**2 - x) > z and ctr <= 100: #print 'low:', low, 'high:', high, 'guess:', guess if guess**2 < x: low = guess else: high = guess guess = (low + high)/2.0 ctr += 1 assert ctr <= 100, 'Ineration count exceeded' print 'Bi method. Num. Interactios', ctr, 'Estimation', guess return guess
sqrtbi(9.0, 0.01): Bi method. Num. Interactios 11 Estimation 3.00146484375 And maybe I'm a little psychotic, but I say it one more time, please use a pastebin to make it easy for us to copy the code. And no need to start a new question, you'd better take into account the answers given to the other one.
you got it dude
http://en.wikipedia.org/wiki/Pastebin Thx for the code, but because I'm a good guy, I reformatted it myself. And tested it too: sqrtbi(9.0, 0.00001) -> Bi method. Num. Interactios 21 Estimation 3.00000143051
lol i understand now... I reformatted your code too well sorry. If you look at the return statement, it is inside the while loop. It should be after the loop, like this: http://pastebin.com/8H6YW4Kn
haha THANK YOU!!!!!
Join our real-time social learning platform and learn together with your friends!