R中的浮点问题? [英] floating point issue in R?

查看:121
本文介绍了R中的浮点问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

为什么这些数字不相等?


下面的表达式评估为0.1,认为大于0.1。

 > (1740 / 600,0) -  1740/600 
[1] 0.1
> (一轮(1740 / 600,0) - 1740/600)<= 0.1
[1] FALSE // ??? !! ???
> (round(1740 / 600,0) - 1740/600)<= 0.1000000000000000000000000000000000000001
[1] TRUE

认为这个问题可能是由于四舍五入的原因,我试着用相同的结果:

 > 3  -  2.9 
[1] 0.1
> (3 - 2.9)<= 0.1
[1] FALSE

如何解决这个问题,而不会欺骗中断?

解决方案

浮点指南


我的数字,比如0.1 + 0.2加上一个好的一轮0.3,而
而不是我得到一个奇怪的结果,如0.30000000000000004?



因为在内部,计算机使用的格式(二进制浮点)
不能准确地表示数字,如0.1,0.2或0.3。

当代码是编译或解释,您的0.1已经是
四舍五入到格式的最接近的数字,这导致甚至在计算发生之前,一个小
舍入误差。



我能做些什么来避免这个问题?

这取决于什么样的计算如果你真的需要你的结果加起来,特别是当
你用金钱工作:使用特殊的十进制数据类型。如果您只是
不希望看到所有这些额外的小数位:只需将显示
的结果格式化为固定的小数位数即可。

  • 如果你没有可用的十进制数据类型,另一种方法是使用整数工作
    ,例如完全以美分计算。但是,这
    是更多的工作,并有一些缺点。

    $ / b

    Possible Duplicate:
    Why are these numbers not equal?

    The below expression, which evaluates to 0.1, is considered larger than 0.1.

    > round(1740/600,0) - 1740/600
    [1] 0.1
    > (round(1740/600,0) - 1740/600) <= 0.1
    [1] FALSE //???!!???
    > (round(1740/600,0) - 1740/600) <= 0.1000000000000000000000000000000000000001
    [1] TRUE
    

    Thinking that the issue might be due to rounding I tried this with the same result:

    > 3 - 2.9
    [1] 0.1
    > (3 - 2.9) <=0.1
    [1] FALSE
    

    So, what gives and how do I fix it without fudging the cutoff?

    解决方案

    From the Floating-Point Guide:

    Why don’t my numbers, like 0.1 + 0.2 add up to a nice round 0.3, and instead I get a weird result like 0.30000000000000004?

    Because internally, computers use a format (binary floating-point) that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all.

    When the code is compiled or interpreted, your "0.1" is already rounded to the nearest number in that format, which results in a small rounding error even before the calculation happens.

    What can I do to avoid this problem?

    That depends on what kind of calculations you’re doing.

    • If you really need your results to add up exactly, especially when you work with money: use a special decimal datatype.
    • If you just don’t want to see all those extra decimal places: simply format your result rounded to a fixed number of decimal places when displaying it.
    • If you have no decimal datatype available, an alternative is to work with integers, e.g. do money calculations entirely in cents. But this is more work and has some drawbacks.

    这篇关于R中的浮点问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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