標籤:python
Lecture5: Floating point number , successive refinement, finding roots 浮點數和二分法
3wschool 數字
>>> a = 2 ** 1000>>> a10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376L>>> b = 2 ** 999>>> b5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688L>>> a/b2L
IEEE 754 floating point
wiki IEEE floating point
wiki IEEE 754 中文
>>> import math>>> a = math.sqrt(2)>>> a1.4142135623730951>>> a * a == 2False
# 大約相等abs(a*a - 2.0) < epsilon
>>> s = 0.0>>> for i in range(10): s += 0.1... >>> s0.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 guessfor iter in range(100): if f(guess) close enough: return guess else: guess = better guesserror
逐次逼近法求平方根
- 二分法,求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
MIT公開課:電腦科學及編程導論 Python 筆記5 浮點數,逐次逼近法和二分法