可能重複:
python - decimal place issues with floats
Python float equality weirdnessPython的怪異除了錯誤
在下面的代碼我有可變percentage
這是一個浮子。我已經建立了這樣,如果number
達到10,000
,percentage
是假設上漲.01
。
# Tries to find a number that when squared and 5%'ed is still a square.
import math
print("Script has started:\n")
percentage = .1
number = 1
while number != -1:
number = number + 1
num_powered = number ** 2
num_5per = num_powered * percentage
num_5per_sqrt = math.sqrt(num_5per)
num_list = list(str(num_5per_sqrt))
dot_location = num_list.index(".")
not_zero = 0
for x in num_list[dot_location + 1:]:
if x != "0":
not_zero = 1
break
if not_zero == 0:
print("*********************************")
print("Map :",number)
print("Safe-Area :",num_5per_sqrt)
print("Percentage :",percentage)
print("*********************************")
input()
if number > 10000:
number = 0
percentage = percentage + .01
print(percentage)
輸出:
0.11
0.12
0.13
0.14
0.15000000000000002 # Here is where it goes crazy
0.16000000000000003
這是非常普遍的。計算機中的浮點數是基數2,並且它們不能精確地表示基數爲10的許多數字。 – 2012-08-08 20:59:15
這不是一個錯誤。這是浮點變量如何工作的結果。請參閱http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html。投票結束重複。 – 2012-08-08 20:59:56
哦,我看到了感謝,然後抱歉Google搜索,但沒有看到重複。 – RandomPhobia 2012-08-08 21:01:37