有人可以用这个功能解释这种行为吗?

Can someone explain this behavior with this function?

>>> def my_max(x,y):
        return ( x + y + abs(x - y)) / 2
>>> my_max(-894,2.3)
2.2999999999999545
>>> my_max(34,77)
77.0
>>> my_max(0.1,0.01)
0.1
>>> my_max(-0.1 , 0.01)
0.009999999999999995

我只是在玩 python,我制作了这个功能,它有时可以工作,而其他功能只是靠近遮阳篷

我知道它与浮点错误有关,但为什么对某些输入有效而对其他输入无效??

分离函数时更容易测试:

def m(x, y):

    first = x + y
    second = abs(x - y)
    third = first + second
    fourth = third / 2

    print("x+y\t\t\t", first)
    print("abs(x-y)\t\t", second)
    print("x+y + abs(x-y)\t\t", third)
    print("(x+y + abs(x-y))/2\t", fourth)

m(-894, 2.3)

您收到以下输出:

x+y                  -891.7
abs(x-y)             896.3
x+y + abs(x-y)       4.599999999999909
(x+y + abs(x-y))/2   2.2999999999999545

现在查看 x+y + abs(x-y) 我们有以下内容:

var = -891.7 + 896.3
print(var)

输出:

4.599999999999909

这当然应该是4.6,但是可以参考Python的文档here

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

您可以使用 Python 附带的 decimal 库解决此问题:

from decimal import *

getcontext().prec = 10
var = Decimal(-891.7) + Decimal(896.3)
print(var)

输出:

4.600000000

在这种情况下,您的精度可以高达 13,以便正确输出 4.6 的变体。将它增加到 14 或更大,您会发现您将再次收到 4.59.....