0

I am struggling about floating points in Rcpp and how to get the numeric output from continued fractions in a numeric vector.

Here is my demo code:

library(Rcpp)
cppFunction('NumericVector signC() {
    NumericVector out1(3);
    out1[0]=round(0.888888888);
    out1[1]=round(1/3);
    out1[2]=1/3;
    return out1;
}')

The output from my demo code:

> signC()
[1] 1 0 0

I am wondering why 1/3 was convert to be 0 and how to get 0.3333333 from 1/3? The 1/3 was working fine under R environment.

Thanks, I appreciate any replies in advance!

daedsidog
  • 1,732
  • 2
  • 17
  • 36
Joanna
  • 663
  • 7
  • 21
  • 2
    In short, C and C++ are a different ("typed") language, and `1/3` behaves differently: it is an integer-only division whereas R casts up to double. So here you want `1.0/3.0` (or having just one as double suffices too: `1.0/3`). – Dirk Eddelbuettel Dec 07 '18 at 15:01
  • Thanks @DirkEddelbuettel. I really appreciate you helping me understand C++. – Joanna Dec 07 '18 at 22:23
  • 1
    My pleasure. These are the little things we all banged our heads against at some point. Live, and learn, and share. Cheers. – Dirk Eddelbuettel Dec 07 '18 at 23:01

0 Answers0