在多种语言中int((0.1+0.7)*10) = 7,如何防止?
最近我发现了几个编程语言中的一个bug或者说是特性。我对它是怎么产生的有一些基本了解(我希望能有更详细的解释),但当我回想起这些年来我可能犯过的所有错误时,我就在想,怎么才能判断“嘿,这可能会导致一个很奇怪的bug,我最好使用任意精度的函数”。还有,其他语言中有没有这个bug(那些没有这个bug的语言,为什么)。另外,为什么0.1加0.7会出现这个问题,而0.1加0.3却不会,有没有其他著名的例子?
PHP
//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
Ruby:
>> ((0.1+0.7)*10).to_i
=> 7
>>((0.1+0.7)*10)
=> 7.999999999999999