R似乎支持浮点数组中的有效NA
值。它如何在内部表示它?
我(也许是有缺陷的)理解是,现代CPU可以在硬件中执行浮点计算,包括有效地处理Inf、-Inf和NaN值。NA
如何适应这一点,如何在不影响性能的情况下实现它?
发布于 2018-08-04 22:30:02
R使用为IEEE floats定义的NaN值来表示NA_real_
、Inf
和NA
。我们可以使用一个简单的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。
https://stackoverflow.com/questions/51684861
复制相似问题