Lecture5: Floating point number , successive refinement, finding roots 浮点数和二分法
3wschool 数字
>>> a = 2 ** 1000
>>> a
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376L
>>> b = 2 ** 999
>>> b
5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688L
>>> a/b
2L
IEEE 754 floating point
- scientific notation
- a mantissa 尾数(0=< mantissa < 2) and an exponent 指数
worry about == on float number!
>>> import math
>>> a = math.sqrt(2)
>>> a
1.4142135623730951
>>> a * a == 2
False
# 大约相等
abs(a*a - 2.0) < epsilon
>>> s = 0.0
>>> for i in range(10): s += 0.1
...
>>> s
0.9999999999999999
Why might this be a challenge? What are some of the issues?
- might not be an exact answer 没有确切的值 例如:sqrt(2)
- can’t enumerate all guesses 无法枚举所有的可能值,因为实数是不可数的
- guess, check, and improve
- successive approximation 逐次逼近法
# 逐次逼近法(伪代码):
guess = inital guess
for iter in range(100):
if f(guess) close enough: return guess
else: guess = better guess
error
逐次逼近法求平方根
- 二分法,求x的平方根,epsilon (ε) 是一个足够小的数,ctr 迭代次数
def squareRootBi(x, epsilon):
"""Assume x >= 0 and epsilon > 0
Return y s.t. y*y is within epsilon(ε) of x"""
assert epsilon > 0, ‘epsilon must be postive, not‘ + str(epsilon)
low = 0
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:
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 squareRootNR(x, epsilon):
"""Return y s.t. y*y is within epsilon of 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:
# 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
时间: 2024-10-08 23:23:30