Python奇怪的加法错误

标签 python floating-point addition

<分区>

Possible Duplicate:
python - decimal place issues with floats
Python float equality weirdness

在下面的代码中,我有变量 percentage,它是一个 float 。我已将其设置为如果 number 达到 10,000percentage 应该增加 .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

最佳答案

来自 the Python docs

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)

你可能应该使用 the decimal module .

关于Python奇怪的加法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11873046/

相关文章:

python - 我的列表或元组或任何类似数据结构中的变量如何将其更改反射(reflect)在列表中?

具有透明度的python opencv cv2 matchTemplate

ios - 为什么 GLSL 的算术函数在 iPad 上与在模拟器上产生如此不同的结果?

java - 如何检查舍入误差?

matlab - 关于浮点精度 : why the iteration numbers are not equal?

java - 如何将sql查询的派生变量添加到java中的列表中

python - Bigtable 还是 Datastore 更适合在线应用程序存储和使用财务数据?

c++ - 调试从 Python 调用的 C++ 代码中的段错误

jquery - 如何使用 jQuery 添加基于 URL 的 "Selected"类?

c - 为什么这个浮点加法结果不正确?