کدهای کلاسی ششم
def squareRootBi(x,epsilon):
'''Assume x>= 0 and epsilon > 0
Return y s.t. y*y is close enough to x'''
assert x>=0, 'input should be nonnegative number, not' + str(x)
assert epsilon > 0, 'epsilon should be positive number, not' + str(epsilon)
low = 0 # lower bound of searching range
high = max(1,x) # upper bound of searching range
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, 'Iteration exceeded'
print 'Bi method. Num. Iteration:',ctr,'Estimate:',guess
return guess
def testBi():
print 'squareRootBi(4,0.0001)'
squareRootBi(4,0.0001)
print 'squareRootBi(9,0.0001)'
squareRootBi(9,0.0001)
print 'squareRootBi(2,0.0001)'
squareRootBi(2,0.0001)
print 'squareRootBi(0.25,0.0001)'
squareRootBi(0.25,0.0001)
def squareRootNR(x,epsilon):
'''Assume x>= 0 and epsilon > 0
Return y s.t. y*y is close enough to x'''
assert x>=0, 'input should be nonnegative number, not' + str(x)
assert epsilon > 0, 'epsilon should be positive number, not' + str(epsilon)
x = float(x)
guess = x/2.0
## guess = 0.01
diff = guess**2 - x
ctr = 1
while abs(diff) > epsilon and ctr<=100:
guess = guess - diff/(2.0*guess)
diff = guess**2 - x
ctr += 1
assert ctr <= 100, 'Iteration exceeded'
print 'NR method. Num. Iteration:',ctr,'Estimate:',guess
return guess