标签:python
注意:
# 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
Bisection methods 二分法:
Newton 求导
guess点的导数 = guess 点的斜率
由上面3个式子得到:
例子:
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
non-scalar types 非基本类型
>>> 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]
MIT公开课: Python 笔记6 二分法,牛顿-拉夫森方法,列表
标签:python
原文地址:http://blog.csdn.net/muzilanlan/article/details/45843563