Search code examples
rrcpplinspace

Rcpp code for "linspace" function: vector length incorrect when increment 1e-5


I want to write a function like "linspace" to create equal interval vectors in R with Rcpp. num_dis here is the number of intervals I want for that vector, i.e., a=0,b=10,num_dis = (10-0)/(1e-5)+1=1000001. When I put linspace(0,10,1000001), the vector length is correct as 1000001; however, when I write like: linspace(0,10,10/(1e-5)+1), it returns a vector of length 100000. For increments like 1e-3,1e-6, etc., it seems good. I am not quite sure what happens?

 NumericVector linspace(double a,double b,int num_dis) {
        NumericVector u(num_dis);
        for (int i = 0; i < num_dis; i++) {
            u[i] = a + i * ((b - a) / (num_dis-1));
        }
        return u;
    }

Solution

  • I think this explains things:

    > as.integer(10/(1e-5)+1)
    [1] 1000000
    > as.integer(10L*1e5L+1L)
    [1] 1000001
    >