浮点数
浮点数都是近似精确,用浮点数表示的数字很难精确的表示该数字本身的值,会有或大或小的偏差。这也很好理解,因为浮点数其实是用科学计数法来表示数字。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)
其运行结果:
###