Python奇怪的添加错误 [英] Python weird addition bug
问题描述
可能重复:
蟒蛇 - 与浮点数的小数位问题
Python浮点平等怪异
在下面的代码中,变量百分比
这是一个浮动。我已经设置好if number
达到 10,000
, percentage
假设是由 .01
。
In the code below I have the variable percentage
which is a float. I have it set up so that the if number
reaches 10,000
, percentage
is suppose to go up by .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)
输出:
Output:
0.11
0.12
0.13
0.14
0.15000000000000002 # Here is where it goes crazy
0.16000000000000003
推荐答案
从 Python文档
请注意,这是二进制浮点的本质:这不是Python中的错误,也不是代码中的错误(强调我的)。在所有语言中,您都会看到支持您的硬件浮点运算的相同类型的东西(尽管有些语言默认情况下可能不会显示差异,或者在所有输出模式下显示差异)
Note that this is in the very nature of binary floating-point: this is not a bug in Python, and it is not a bug in your code either (emphasis mine). You’ll see the same kind of thing in all languages that support your hardware’s floating-point arithmetic (although some languages may not display the difference by default, or in all output modes)
您应该使用 小数
模块。
You should probably use the decimal
module.
这篇关于Python奇怪的添加错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!