1

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;
    }
Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
Kevin
  • 17
  • 4

2 Answers2

1

This already exists as an Armadillo function you can call. (The line of code is broken over two lines here for display, it really is one.)

R> Rcpp::cppFunction("arma::vec ls(double s, double e, int N) { 
       return arma::linspace(s, e, N); }", depends="RcppArmadillo")
R> ls(1,2, 10)
         [,1]
 [1,] 1.00000
 [2,] 1.11111
 [3,] 1.22222
 [4,] 1.33333
 [5,] 1.44444
 [6,] 1.55556
 [7,] 1.66667
 [8,] 1.77778
 [9,] 1.88889
[10,] 2.00000
R> 

That said, getting the "index math" expressions right is always a nice debugging exercise.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
1

I think this explains things:

> as.integer(10/(1e-5)+1)
[1] 1000000
> as.integer(10L*1e5L+1L)
[1] 1000001
> 
Erwin Kalvelagen
  • 15,677
  • 2
  • 14
  • 39