Question

I have a block of R code that I rewrote in C, and the two versions provide different results. My belief is that this is due to rounding issues at the R level, i.e. multiple math operations are being performed which creates compounded rounding issues as opposed to the whole thing being done in C and rounding only occurring once. I'm afraid that I'm being overly optimistic here and was hoping for some more sets of eyes to see if I'm missing something and it's actually just poor coding on my end.

First the R code:

h_tx <- function(x, sigma_nu, sigma_eta, alpha=0) {
   b <- (sqrt(exp(sigma_eta^2) - 1)) / sigma_nu
   a <- -alpha * b
   asinh(a+b*x)
}

Now in C:

double hTx(double x, double sigmaNu, double sigmaEta, double alpha) {
  double a;
  double b;
  double ret;

  b = (sqrt(exp(pow(sigmaEta,2)-1))) / sigmaNu;
  a = -alpha * b;
  return asinh(a + b * x);
}

As an example, passing in values 5, 5, 5, 0 gives 13.19 in R and 12.69 in C. Technically the R code is vectorized but this particular block of C code is not so I don't want to provide a vectorized input as an example.

Are these functionally the same, or am I doing something incorrect?

Was it helpful?

Solution

Your expressions are different:

       b <- (sqrt(exp(sigma_eta^2) - 1)) / sigma_nu
            1    2   3-----------3    21
             \    \------------------//
              \----------------------/

The -1 is in the group 2 of parenthesis: the sqrt

       b = (sqrt(exp(pow(sigmaEta,2)-1))) / sigmaNu;
           1    2   3   4----------4  321
            \    \   \---------------///
             \    \------------------//
              \----------------------/

The -1 is in the group 3 of parenthesis: the exp

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top