R内部如何表示NA?

问题描述 投票:0回答:1

R 似乎支持浮点数组中高效的

NA
值。它内部是如何表示的?

我(也许有缺陷)的理解是,现代CPU可以在硬件中进行浮点计算,包括有效处理Inf、-Inf和NaN值。

NA
如何适应这一点,以及如何在不影响性能的情况下实现它?

r floating-point na internal-representation
1个回答
3
投票

使用 IEEE floats

+Inf
-Inf
时,指数中的所有位(第二位到 13 位)都设置为 1,尾数中的所有位设置为 0,而 NaN 具有非零尾数。 R 使用不同的尾数值来表示
NaN
以及
NA_real_
。我们可以使用一个简单的 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_)
#> 7ff00000000007a2
print_hex(NaN)
#> 7ff8000000000000
print_hex(Inf)
#> 7ff0000000000000
print_hex(-Inf)
#> fff0000000000000

这里有一些来源 代码 参考文献

© www.soinside.com 2019 - 2024. All rights reserved.