【问题标题】:Which algorithm does R use under the hood to calculate the variance?R 在底层使用哪种算法来计算方差?
【发布时间】:2022-01-22 15:09:05
【问题描述】:

计算数据样本x 的方差的算法在数值上的鲁棒性和精确度越来越低。比如有一个精度很高的公式(见下面的参考文献),大致相当于

( sum((x - mean(x))^2) - (sum(x - mean(x))^2)/length(x) )/length(x)

这有点低效,因为它两次遍历数据。另一方面,数学上等价的公式mean(x^2)-mean(x)^2 更容易发生灾难性的取消。还有许多其他算法,其中一些只对数据进行一次传递;例如查看Chan, Golub, LeVequeLing 中的评论。

R 在底层使用哪种算法来计算函数var() 的方差?我阅读了该函数的手册页,但他们没有说明所使用的特定算法。我不是程序员,很难理解底层 C 代码中发生的事情。

【问题讨论】:

    标签: r algorithm precision variance


    【解决方案1】:

    如果您正在寻找stats::var,只需输入即可。

    stats::var
    
    function (x, y = NULL, na.rm = FALSE, use) 
    {
        if (missing(use)) 
            use <- if (na.rm) 
                "na.or.complete"
            else "everything"
        na.method <- pmatch(use, c("all.obs", "complete.obs", 
            "pairwise.complete.obs", "everything", "na.or.complete"))
        if (is.na(na.method)) 
            stop("invalid 'use' argument")
        if (is.data.frame(x)) 
            x <- as.matrix(x)
        else stopifnot(is.atomic(x))
        if (is.data.frame(y)) 
            y <- as.matrix(y)
        else stopifnot(is.atomic(y))
        .Call(C_cov, x, y, na.method, FALSE)
    }
    <bytecode: 0x000001f7636f08f8>
    <environment: namespace:stats>
    

    .Call(C_cov,...) 中,它调用C 对象cov.c。您可以在该链接中找到var 的算法。

    【讨论】:

      猜你喜欢
      • 2020-02-09
      • 1970-01-01
      • 2014-10-06
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      • 2012-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多