int((0.1+0.7)*10) = 7 几种语言.如何防止这种情况? [英] int((0.1+0.7)*10) = 7 in several languages. How to prevent this?

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

问题描述

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

PHP

//第一个对我来说实际上没有任何意义,//如果在内部表示为 8,为什么在类型转换后是 7?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)

蟒蛇:

<预><代码>>>>((0.1+0.7)*10)7.9999999999999991>>>整数((0.1+0.7)*10)7

Javascript:

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

红宝石:

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

解决方案

什么每个计算机科学家都应该了解浮点运算

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:

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                                                    

解决方案

What Every Computer Scientist Should Know About Floating-Point Arithmetic

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

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