Lecture 6: Bisection methods, Newton/Raphson, introduction to lists
程序员文章站
2022-07-12 17:15:51
...
# example code, Lecture 6, Fall 2008
s = 0
for i in range(10):
s += 0.1
print (s)
def squareRootBi(x,epsilon):
'''Assumes x >= 0 and epsilon > 0
return y s.t. y*y is within epsilon of x'''
assert x >= 0, 'x must be non-negative, not' + str(x)
assert epsilon > 0, 'epsilon must be postive, not' + str(epsilon)
low = 0
high = max(x, 1.0)
guess = (low + high)/2.0
ctr = 1
while abs(guess**2 - x) > epsilon and ctr <= 100:
#epsilon is the smallest value to approximate the square
if guess**2 < x:
low = guess
else:
high = guess
guess = (low + high)/2.0
ctr += 1
assert ctr <= 100, 'Iteration count exceeded'
print ('Bi method. Num. iterations:', ctr, 'Estimate:', guess)
return guess
def testBi():
print ('squareRootBi(4, 0.001)')
squareRootBi(4,0.001)
print ('squareRootBi(9, 0.001)')
squareRootBi(9, 0.001)
print ('squareRootBi(2, 0.001)')
squareRootBi(2, 0.001)
print ('squareRootBi(0.25, 0.0001)')
squareRootBi(0.25, 0.0001)
def squareRootNR(x, epsilon):
assert x >= 0, 'a must be non-negative, not' + str(x)
assert epsilon > 0, 'epsilon must be postive, not' + 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:
guess = guess - diff/(2.0*guess)
diff = guess**2 - x
ctr += 1
assert ctr <= 100, 'Iteration count exceeded'
print ('NR method. Num. iterations:', ctr, 'Estimate:', guess)
return guess
def compareMethods():
print ('squareRoot(2, 0.01)')
squareRootBi(2, 0.01)
squareRootNR(2, 0.01)
input()
print ('squareRoot(2, 0.0001)')
squareRootBi(2, 0.001)
squareRootNR(2, 0.001)
input ()
print ('squareRoot(2, 0.000001)')
squareRootBi(2, 0.000001)
squareRootNR(2, 0.000001)
input ()
print ('squareRoot(1234567890, 0.0001)')
squareRootBi(1234567890, 0.0001)
squareRootNR(1234567890, 0.0001)
input ()
print ('squareRoot(1234567890, 0.000001)')
squareRootBi(1234567890, 0.000001)
squareRootNR(1234567890, 0.000001)
input ()
print ('squareRoot(2736336100, 0.0001)')
squareRootBi(2736336100, 0.0001)
squareRootNR(2736336100, 0.0001)
def showLists():
Techs = ['MIT', 'Cal Tech']
print (Techs)
input()
Ivys = ['Harvard', 'Yale', 'Brown']
print (Ivys)
input()
Univs = []
Univs.append(Techs)
print (Univs)
input()
Univs.append(Ivys)
print (Univs)
input()
for e in Univs:
print (e)
for c in e: print (c)
input()
Univs = Techs + Ivys
print (Univs)
input()
Univs.remove('Harvard')
print (Univs)
def list():
list = ["A", "B", "C", "B", "D"]
list.remove("B")
print (list)