開始使用免費開始

double 向量的總和

因為在 C++ 中的迴圈通常比 R 快很多,所以撰寫迴圈是一項重要技能。先來寫一個從 NumericVector 加總數值的函式。這會複習你在第 2 章練習 10,以及本章前一個練習中學到的技巧。

本練習屬於課程

用 Rcpp 最佳化 R 程式碼

檢視課程

練習說明

  • 完成函式 sum_cpp 的定義,讓它遍歷 NumericVector 的各元素並回傳總和。
    • n 設為 xsize()
    • result 初始化為 0。
    • 指定 for 迴圈的引數。將 i 初始化為 0,設定迭代條件為 i 小於 n,每步將 i 加 1。
    • 在每次迭代中,把 x 的第 i 個元素加到 result

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

#include 
using namespace Rcpp;

// [[Rcpp::export]]
double sum_cpp(NumericVector x) {
  // The size of x
  int n = ___;
  // Initialize the result
  double result = ___;
  // Complete the loop specification
  for(int i = 0; ___; ___) {
    // Add the next value
    result = result + ___;
  }
  return result;
}

/*** R
set.seed(42)
x <- rnorm(1e6)
sum_cpp(x)
# Does the function give the same answer as R's sum() function?
all.equal(sum_cpp(x), sum(x))
*/
編輯並執行程式碼