简体   繁体   English

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

[英]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

I am just playing around with python and i made this function that it sometimes works and others it just gets close to the awnser我只是在玩 python,我做了这个 function,它有时可以工作,而其他的它只是靠近 awnser

I know it has to do with floating-point errors, but why would work for some inputs and not in others??我知道它与浮点错误有关,但为什么对某些输入有效,而对其他输入无效?

Easier to test this out when you separate the function:将 function 分开时更容易测试:

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)

You receive the following outputs:您会收到以下输出:

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

Now looking at x+y + abs(xy) we have the following:现在看x+y + abs(xy)我们有以下内容:

var = -891.7 + 896.3
print(var)

Which outputs:哪个输出:

4.599999999999909

This should, of course, be 4.6 , but what is happening can be referred from Python's documentation here :当然,这应该是4.6 ,但是可以从 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.请注意,这是二进制浮点的本质:这不是 Python 中的错误,也不是您的代码中的错误。 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).您将在所有支持硬件浮点运算的语言中看到相同的内容(尽管某些语言默认情况下可能不显示差异,或者在所有 output 模式下)。

You can resolve this by utilizing the decimal library that comes with Python:您可以使用 Python 附带的decimal库来解决此问题:

from decimal import *

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

outputs:输出:

4.600000000

In this case, your precision can be as large as 13 for it to correctly output a variation of 4.6 .在这种情况下,您的精度可以高达 13 以使其正确 output 变体4.6 Increase it to 14 or larger and you will notice you will once again receive your 4.59.... .将其增加到 14 或更大,您会注意到您将再次收到4.59....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM