Implementing the following functionality in R

Is there any implementation of the functionality in R, so that you can get the next representable floating-point number from a given floating-point number. This would be similar to the nextafter function in the C standard library. Schemas such as this number + .Machine$double.epsdo not work at all.

+4
source share
2 answers

No, but you can do two ways:

Using c

If you want the exact functionality of a function nextafter(), you can write a C function that acts as an interface to the function, so the following two restrictions are true:

  • . " " ( ).
  • - . ( ) R.

:

R CMD SHLIB foo.c

UNIX- . dyn.load("foo.so"). R, .C()

.C("foo", ...)

C R .

R

number + .Machine$double.eps - , , if x - y < .Machine$double.eps if x == y. ​​:

nextafter <- function(x, y){
  # Appropriate type checking and bounds checking goes here
  delta = y - x
  if(x > 0){
    factor = 2^floor(log2(x)) + ifelse(x >= 4, 1, 0)
      } else if (x < 0) {
    factor = 65
  }
  if (delta > .Machine$double.eps){
    return(x + factor * .Machine$double.eps)
  } else if (delta < .Machine$double.eps){
    return(x - factor * .Machine$double.eps)
  } else {
    return(x)
  }
}

, C, , , .

UPDATE , , , 2. , .Machine$double.eps, , . 2 . , :

n <- -100
factor <- vector('numeric', 100)
for(i in 1:n){
  j = 0
  while(TRUE){
    j = j + 1
    if(i - j * .Machine$double.eps != i) break()
  }
  factor[i] = j
}  
+4

Rcpp:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double nextAfter(double x, double y) {
   return nextafter(x, y);
}

R:

sprintf("%.20f", 1)
#[1] "1.00000000000000000000"
sprintf("%.20f", nextAfter(1, 2))
#[1] "1.00000000000000022204"
+3

Source: https://habr.com/ru/post/1529015/


All Articles