【发布时间】:2020-02-23 04:54:24
【问题描述】:
>>> 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,我做了这个函数,它有时可以工作,而其他的它只是靠近 awnser
我知道这与浮点错误有关,但为什么对某些输入有效而对其他输入无效??
【问题讨论】:
-
why would work for some inputs and not in others?——因为有些数字可以用浮点数精确表示,有些则不能。其中,有些是在您将它们打印到您的预期时近似的,而有些则不是。 -
我建议尝试使用
my_max(-1.0e100,1.0e10)来了解并非所有数学公式都在浮点运算中表现良好。你明白为什么吗?
标签: python python-3.x floating-point floating-accuracy