Lecture5: Bisection methods , Newton/Raphson, introduction to lists二分法,牛顿,拉复生方法,列表
Bisection methods 二分法
注意:
# bug: when x < 1, sqrt(x) > x = high eg.x=0.25 sqrt(x) = 0.5
# fix bug: high = max(x, 1.0)
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 positive, not‘ + str(epsilon)
low = 0
# bug: when x < 1, sqrt(x) > x = high eg.x=0.25 sqrt(x) = 0.5
# fix bug: high = max(x, 1.0)
high = x
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 count exceeded‘
print ‘Bi method. Num. iterations:‘, ctr, ‘Estimate:‘, guess
return guess
Newton Raphson 牛顿-拉夫森方法
Bisection methods 二分法:
Δ(guess)=guess2?x
Δ(guess)=0
Newton 求导
guess点的导数 = guess 点的斜率
Δ′(guess)=2guessi=k
k=Δ(guessi)guessi+1?guessi
Δ(guessi)=guess2i?x
由上面3个式子得到:
guessi+1=guessi?Δ(guessi)2guessi
例子:
Δ(3)=32?16=?7
guessi+1=3?Δ(3)2×3=4.1666
def squareRootNR(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 positive, 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:
# print ‘Error:‘, diff, ‘guess:‘, guess
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
Lists 列表
non-scalar types 非基本类型
- Tuple 元组 (immutable 不可改变的)
- String 字符串(immutable 不可改变的)
- List 列表 (mutable 可改变的)
>>> Techs = [‘MIT‘, ‘Cal Tech‘]
>>> print Techs
[‘MIT‘, ‘Cal Tech‘]
>>> Ivys = [‘Harvard‘, ‘Yale‘, ‘Brown‘]
>>> print Ivys
[‘Harvard‘, ‘Yale‘, ‘Brown‘]
>>> Univs = []
>>> Univs.append(Techs)
>>> print Univs
[[‘MIT‘, ‘Cal Tech‘]]
>>> Univs.append(Ivys)
>>> print Univs
[[‘MIT‘, ‘Cal Tech‘], [‘Harvard‘, ‘Yale‘, ‘Brown‘]]
for e in Univs:
print e
for c in e: print c
[‘MIT‘, ‘Cal Tech‘]
MIT
Cal Tech
[‘Harvard‘, ‘Yale‘, ‘Brown‘]
Harvard
Yale
Brown
>>> Univs = Techs + Ivys
>>> print Univs
[‘MIT‘, ‘Cal Tech‘, ‘Harvard‘, ‘Yale‘, ‘Brown‘]
>>> Ivys.remove(‘Harvard‘)
>>> print Ivys
[‘Yale‘, ‘Brown‘]
>>> Ivys[1] = -1
>>> print Ivys
[‘Yale‘, -1]
时间: 2024-10-31 19:13:36