# ShowSqrtWhile.py """ Checks out an implementation of a sqrt function implementation that is based on a while loop. """ # You can rename an imported function like this... from math import sqrt as TrueSqrt def sqrt(x): """ The square root of x and the number of iterations required. Example: (y,iterations) = sqrt(10) Precondition: x is a positive float or int """ L=float(x) W=1.0 relErr = 10e-15 its=0 itMax = 200 while abs(L-W)/L > relErr and its<=itMax: L = (L+W)/2 W = x/L its+=1 # How a function can return "more than one thing... return (L,its) # Test Script if __name__=='__main__': print '\n\n x sqrt(x) relError iterations' print '----------------------------------------------------------------' k = -17 while k<15: k+=2 x = 10.0**k # How to process a function that can return more than one thing... (y,iterations) = sqrt(x) # TrueSqrt is "really" math.sqrt... yExact = TrueSqrt(x) relErr = abs(y - yExact)/yExact print '%8.1e %20.12e %8.3e %3d' % (x,y,relErr,iterations)