程序計算時,精度問題

浮點數

浮點數都是近似精確,用浮點數表示的數字很難精確的表示該數字本身的值,會有或大或小的偏差。這也很好理解,因爲浮點數其實是用科學計數法來表示數字。float類型和int都是32-bit,因此它們能表示的數字的數量是一樣的。但是浮點數增加了其所表徵數的範圍,因此分辨率會相應的下降。這裏給出一個例子

too_small = []
just_right = []
too_large = []

n = 1
while len(too_small) < 10 or len(just_right) < 10 or len(too_large) < 10:
    sqrt_n = sqrt(n)
    if sqrt_n ** 2 < n and len(too_small) < 10:
        too_small.append((n, sqrt_n, sqrt_n ** 2))
    elif sqrt_n ** 2 == n and len(just_right) < 10:
        just_right.append((n, sqrt_n, sqrt_n ** 2))
    else:
        too_large.append((n, sqrt_n, sqrt_n ** 2))        
    n += 1

print('Too small!')
for triple in too_small:
    print(triple)
print('\nJust right!')
for triple in just_right:
    print(triple)
print('\nToo large!')
for triple in too_large:
    print(triple)

其運行結果:
###這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章