一种是二分查找的使用
二分法,在很多排序,查找等问题中经常使用
def squareRootBi(x, epsilon): """Assume x >= 0 and epsilon > 0 Return y s.t. y*y is within epsilon of x""" #假设x>=0且ε>0,返回y,使得y*y在x的ε内 assert x >= 0, 'x必须为非负数,而不是' + str(x) assert epsilon > 0, 'ε必须为正数,而不是' + str(epsilon) low = 0 high = x #high = max(x,1) guess = (low + high)/2.0 ctr = 1 while abs(guess**2 - x) > epsilon 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, '循环计数次数超出范围' print 'Bi方法,循环数', ctr, '估值', guess return guess
另外一种,是求切点的值的思路,使用了牛顿迭代法
def squareRootNR(x, epsilon): """Assume x >= 0 and epsilon > 0 Return y s.t. y*y is within epsilon of x""" #假设x>=0且ε>0,返回y,使得y*y在x的ε内 assert x >= 0, 'x必须为非负数,而不是' + str(x) assert epsilon > 0, 'ε必须为正数,而不是' + str(epsilon) x = float(x) guess = x/2.0 #guess = 0.001 diff = guess**2 -x ctr = 1 while abs(diff) > epsilon and ctr <= 100: #print '差值:', diff, '猜想值:', guess guess = guess - diff/(2.0*guess) diff = guess**2 - x ctr += 1 assert ctr <=100, '循环计数次数超出范围' print 'NR方法,循环数', ctr, '估值', guess return guess