Class activity solutions

Author

Ciaran Evans

Rcpp::cppFunction('double weighted_sum(NumericVector x, NumericVector w){
  int n = x.size();
  double sum = 0;
  
  for(int i = 0; i < n; ++i){
    sum += x[i]*w[i];
  }
  
  return sum;
}')
x <- rnorm(1000)
w <- runif(1000)

bench::mark(
  weighted_sum(x, w),
  sum(x * w),
  crossprod(x, w),
  check = F
)
# A tibble: 3 × 6
  expression              min   median `itr/sec` mem_alloc `gc/sec`
  <bch:expr>         <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
1 weighted_sum(x, w)   2.46µs   3.33µs   297448.    2.49KB     0   
2 sum(x * w)         112.67µs 114.71µs     8621.    7.86KB     2.03
3 crossprod(x, w)      2.58µs   2.75µs   355831.    2.23KB     0   
Rcpp::cppFunction('double varC(NumericVector x){
  int n = x.size();
  
  double mean = 0;
  
  for(int i = 0; i < n; ++i){
    mean += x[i]/n;
  }
  
  double sum = 0;
  
  for(int i = 0; i < n; ++i){
    sum += pow(x[i] - mean, 2);
  }
  
  return sum/(n-1);
}')
x <- rnorm(1000)

bench::mark(
  var(x),
  varC(x)
)
# A tibble: 2 × 6
  expression      min   median `itr/sec` mem_alloc `gc/sec`
  <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
1 var(x)     325.25µs  326.5µs     3013.   13.71KB        0
2 varC(x)      3.12µs    3.5µs   266347.    2.49KB        0
Rcpp::cppFunction('NumericMatrix matrix_prod(NumericMatrix A, NumericMatrix B){
  int ncol_a = A.ncol();
  int nrow_a = A.nrow();
  int ncol_b = B.ncol();
  int nrow_b = B.nrow();
  
  NumericMatrix result(nrow_a, ncol_b);
  
  for(int i = 0; i < nrow_a; ++i){
    for(int j = 0; j < ncol_b; ++j){
      double sum = 0;
      for(int k = 0; k < ncol_a; ++k){
        sum += A(i,k)*B(k,j);
      }
      
      result(i,j) = sum;
    }
  }
  
  return result;
}')


A <- matrix(rnorm(10), nrow=2, ncol=5)
B <- matrix(rnorm(15), nrow=5, ncol=3)

A %*% B
          [,1]       [,2]      [,3]
[1,]  0.509605 -3.5915745 -5.808356
[2,] -1.572469  0.2583574 -2.714978
matrix_prod(A, B)
          [,1]       [,2]      [,3]
[1,]  0.509605 -3.5915745 -5.808356
[2,] -1.572469  0.2583574 -2.714978