# SqrtDemo.py # Charles Van Loan (cfv3) # January 1, 2015 """ This module compares math.sqrt with a sqrt function that is based on (at most) twenty averaging steps. """ import math def sqrt(x): """ The square root of x. Performs at most 20 steps of Newton's method. Unless x is very large or very small, a relative accuracy of 10e-12 (or better) is achieved. 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 return L # Test Script if __name__=='__main__': print '\n\n x sqrt(x) relError' print '------------------------------------------------------' k = -17 while k<15: k+=2 x = 10.0**k MySqrt = sqrt(x) TrueSqrt = math.sqrt(x) relErr = abs(MySqrt - TrueSqrt)/TrueSqrt print '%8.1e %20.12e %8.3e' % (x,sqrt(x),relErr)