几种语言中的int((0.1+0.7)*10)=7。如何预防?

2024-05-08 15:23:19 发布

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

最近我遇到了一个用几种语言编写的bug/特性。我对它是如何造成的有一个非常基本的了解(我想做一些详细的解释),但是当我想到这些年来我必须犯下的所有错误时,问题是我如何确定“嘿,这可能会导致一个棘手的错误,我最好使用任意精度函数”,其他语言都有这个错误(以及那些不知道的人,为什么)。另外,为什么0.1+0.7会这样,也就是说0.1+0.3不会,还有其他著名的例子吗?

菲律宾比索

//the first one actually doesn't make any sense to me,
//why 7 after typecast if it's represented internally as 8?
debug_zval_dump((0.1+0.7)*10); //double(8) refcount(1)
debug_zval_dump((int)((0.1+0.7)*10)); //long(7) refcount(1)
debug_zval_dump((float)((0.1+0.7)*10)); //double(8) refcount(1)

Python:

>>> ((0.1+0.7)*10)
7.9999999999999991
>>> int((0.1+0.7)*10)
7

Javascript代码:

alert((0.1+0.7)*10); //7.999999999999999
alert(parseInt((0.7+0.1)*10)); //7

红宝石:

>> ((0.1+0.7)*10).to_i                                                  
=> 7                                                                    
>>((0.1+0.7)*10)                                                       
=> 7.999999999999999                                                    

Tags: to函数debug语言错误精度alert特性