【问题标题】:How does R represent NA internally?R如何在内部表示NA?
【发布时间】:2019-01-12 01:39:59
【问题描述】:

R 似乎支持浮点数组中的有效NA 值。它在内部是如何表示的?

我的(也许是有缺陷的)理解是现代 CPU 可以在硬件中执行浮点计算,包括有效处理 Inf、-Inf 和 NaN 值。 NA 如何适应这一点,如何在不影响性能的情况下实现它?

【问题讨论】:

    标签: r floating-point na internal-representation


    【解决方案1】:

    R 使用为 IEEE floats 定义的 NaN 值来表示 NA_real_InfNA。我们可以使用一个简单的 C++ 函数来明确说明这一点:

    Rcpp::cppFunction('void print_hex(double x) {
        uint64_t y;
        static_assert(sizeof x == sizeof y, "Size does not match!");
        std::memcpy(&y, &x, sizeof y);
        Rcpp::Rcout << std::hex << y << std::endl;
    }', plugins = "cpp11", includes = "#include <cstdint>")
    print_hex(NA_real_)
    #> 7ff80000000007a2
    print_hex(Inf)
    #> 7ff0000000000000
    print_hex(-Inf)
    #> fff0000000000000
    

    指数(直到 13 位的第二个)全为 1。这是 IEEE NaN 的定义。但是,虽然Inf 的尾数全为零,但NA_real_ 的情况并非如此。这里有一些source code references.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-07
      • 1970-01-01
      • 2012-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多