MIT公開課:計算機科學及編程導論 Python 筆記5 浮點數,逐次逼近法和二分法

Lecture5: Floating point number , successive refinement, finding roots 浮點數和二分法


3wschool 數字
Python入門篇之數字

>>> a = 2 ** 1000
>>> a
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376L
>>> b = 2 ** 999
>>> b
5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688L
>>> a/b
2L

IEEE 754 floating point
wiki IEEE floating point
wiki IEEE 754 中文

  • 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:
            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
發佈了76 篇原創文章 · 獲贊 64 · 訪問量 36萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章