代码之家  ›  专栏  ›  技术社区  ›  Bogaso

从R中的sum()和'+'获得不同的结果

sum r
  •  2
  • Bogaso  · 技术社区  · 3 年前

    下面是我的实验:

    > xx = 293.62882204364098
    > yy = 0.086783439604999998
    > print(xx + yy, 20)
    [1] 293.71560548324595175
    > print(sum(c(xx,yy)), 20)
    [1] 293.71560548324600859
    

    我觉得很奇怪 sum() + 当两者应用于相同的数字时,给出不同的结果。

    这是预期的结果吗?

    我怎样才能得到同样的结果?

    2 回复  |  直到 3 年前
        1
  •  3
  •   Ben Bolker    3 年前

    有一个 r-devel thread here from Tomas Kalibera :

    R为蓄能器使用长双型(在其所在的平台上 “在可能的情况下,使用扩展精密蓄能器,通常为井式蓄能器 C99及更新版本支持,但可能依赖于平台。”

    这意味着 sum() 非常担心

    here 在经历了一些错误的开始之后,我最终发现 + 是由于使用了扩展精度

    This code 显示单个元素的总和(如 sum(xx,yy) 加上 (C)中,鉴于 this code 用于对单个组件求和;第154行( LDOUBLE s=0.0

        2
  •  2
  •   Jon Spring    3 年前

    看起来加法的速度是求和的3倍,但除非你做高频交易,否则我看不出这会成为你的时间瓶颈。

    xx = 293.62882204364098
    yy = 0.086783439604999998
    
    microbenchmark::microbenchmark(xx + yy, sum(xx,yy), sum(c(xx, yy)))
    Unit: nanoseconds
               expr min    lq   mean median    uq  max neval
            xx + yy  88 102.5 111.90  107.0 110.0  352   100
        sum(xx, yy) 201 211.0 256.57  218.5 232.5 2886   100
     sum(c(xx, yy)) 283 297.5 330.42  304.0 311.5 1944   100
    
        3
  •  0
  •   TarJae    3 年前

    除了这里提供的答案之外,我想提出我的想法:

    据我所知,这是因为DOUBLE使用53位(大约16位)工作

    # both xx and yy are double type
    typeof(print(xx + yy, 20))
    typeof(print(sum(c(xx,yy)), 20))
    
    # all values with after comma places > 16 will give different results
    print(xx + yy, 17)
    print(sum(c(xx,yy)), 17)
    
    #[1] 293.71560548324595
    #[1] 293.71560548324601
    
    # all values with after comma places <= 16 will give identical results
    print(xx + yy, 16)
    print(sum(c(xx,yy)), 16)
    
    #[1] 293.715605483246
    #[1] 293.715605483246
    
    # As far as I know this is because DOUBLE works with 53 bits (about 16 digits)