计算float并存储到list会给出奇怪的值?

2024-04-25 16:52:11 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我开始建立一个函数,我的目标是纠正前3个'分配'超过一定的限制。你知道吗

下面的函数现在返回一个列表,其中所传递的列表中的每个值都有超出的值。你知道吗

def correct_wrong_allocations_zw(weight_vect):
    temp_weight_vect = list(weight_vect[:3])

    limits = [1.00, 0.30, 0.25]
    too_much_list = []

    too_much = 0.00
    for i in range(0, len(temp_weight_vect)):
        if temp_weight_vect[i] > limits[i]:
            too_much_list.append(temp_weight_vect[i]-limits[i])

    return too_much_list

allocations = [0.10, 0.40, 0.50, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00]
allocations = correct_wrong_allocations_zw(allocations)
print allocations

分配[1]和限制[1]之间的差值为0.10,但此程序的结果是:

[0.10000000000000003, 0.25]

怎么回事?你知道吗


Tags: 函数目标列表deftemplisttooweight
1条回答
网友
1楼 · 发布于 2024-04-25 16:52:11

这个Floating Point Arithmetic: Issues and Limitations可能会有帮助。你知道吗

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. 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).


顺便说一句,您可以使用模块decimal查看存储在任何特定Python float中的确切值。就你而言

>>> from decimal import Decimal
>>> Decimal(0.4-0.3)
Decimal('0.100000000000000033306690738754696212708950042724609375')

相关问题 更多 >