几种语言的int((0.1 + 0.7)* 10)= 7。怎么预防这个? [英] int((0.1+0.7)*10) = 7 in several languages. How to prevent this?

查看:316
本文介绍了几种语言的int((0.1 + 0.7)* 10)= 7。怎么预防这个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我遇到了几种语言的错误/功能。我对它是如何引起的有一个非常基本的了解(我想要一些详细的解释),但是当我想到多年来我必须犯下的所有错误时,问题是如何确定 嘿,这可能会导致一个荒谬的bug,我最好使用任意精确函数 ,其他语言确实有这个bug(而那些没有,为什么)。另外,为什么0.1 + 0.7会这样做,即0.1 + 0.3没有,还有其他众所周知的例子吗?

Recently I came across a bug/feature in several languages. I have a very basic knowledge about how it's caused (and I'd like some detailed explanation), but when I think of all the bugs I must have made over the years, the question is how can I determine "Hey, this might cause a riddiculous bug, I'd better use arbitrary precision functions", what other languages do have this bug (and those who don't, why). Also, why 0.1+0.7 does this and i.e. 0.1+0.3 doesn't, are there any other well-known examples?

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:

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                                                    


推荐答案

每个计算机科学家应该知道的关于浮点运算的知识

这篇关于几种语言的int((0.1 + 0.7)* 10)= 7。怎么预防这个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆