開始使用免費開始

加權平均(C++ 版本)

現在該動手實作:撰寫一個函式來計算向量的加權平均。

給定數值向量 x(資料值)與數值向量 w(權重),加權平均是「資料值乘上權重的總和」除以「權重的總和」。注意,xw 應該有相同的元素個數。

在 R 中可用 weighted.mean() 計算,相當於 sum(x * w) / sum(w)

本練習屬於課程

用 Rcpp 最佳化 R 程式碼

檢視課程

練習說明

  • 完成 weighted_mean_cpp() 函式的定義。
    • total_xwtotal_w 初始化為 0,n 設為 x 的大小。
    • for 迴圈指定引數,使用整數 i 作為計數器。
    • 在迴圈內,將第 i 個權重加到 total_w,並將第 i 個資料值乘以第 i 個權重的結果加到 total_xw
    • 回傳「總乘積除以總權重」的結果。

動手互動練習

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

#include 
using namespace Rcpp;

// [[Rcpp::export]]
double weighted_mean_cpp(NumericVector x, NumericVector w) {
  // Initialize these to zero
  double total_w = ___;
  double total_xw = ___;
  
  // Set n to the size of x
  int n = ___;
  
  // Specify the for loop arguments
  for(int i = 0; ___) {
    // Add ith weight
    total_w += ___;
    // Add the ith data value times the ith weight
    total_xw ___;
  }
  
  // Return the total product divided by the total weight
  return ___;
}

/*** R 
x <- c(0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11)
w <- 1 / seq_along(x)
weighted_mean_cpp(x, w)
# Does the function give the same results as R's weighted.mean() function?
all.equal(weighted_mean_cpp(x, w), weighted.mean(x, w))
*/
編輯並執行程式碼