開始使用免費開始

ARMA(p, q)模型

「自我迴歸移動平均」模型(ARMA(p, q))同時結合自我迴歸(AR(p))與移動平均(MA(q))為一體。模擬向量目前的數值同時取決於該向量過去的數值,以及雜訊向量過去的數值。

請完成 arma() 的函式定義。

本練習屬於課程

用 Rcpp 最佳化 R 程式碼

檢視課程

練習說明

  • 定義整數變數 start,等於 pq 的最大值再加 1。提示:max() 位於 std 命名空間。
  • 在外層 for 迴圈中,定義 double 變數 value,其值為 mu 加上第 i 個雜訊值。
  • 在第一個內層 for 迴圈中,將 value 加上 theta 的第 j 個元素乘以 eps 的「第 i 減 j 減 1」個元素。
  • 在第二個內層 for 迴圈中,將 value 加上 phi 的第 j 個元素乘以 x 的「第 i 減 j 減 1」個元素。

動手互動練習

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

#include 
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector arma(int n, double mu, NumericVector phi, NumericVector theta, double sd) {
  int p = phi.size();
  int q = theta.size();   
  NumericVector x(n);
  
  // Generate the noise vector
  NumericVector eps = rnorm(n, 0.0, sd);
  
  // Start at the max of p and q plus 1
  ___
  
  // Loop i from start to n
  for(int i = start; i < n; i++) {
    // Value is mean plus noise
    ___
    
    // The MA(q) part
    for(int j = 0; j < q; j++) {
      // Increase by the jth element of theta times
      // the "i minus j minus 1"th element of eps
      ___
    }
    
    // The AR(p) part
    for(int j = 0; j < p; j++) {
      // Increase by the jth element of phi times
      // the "i minus j minus 1"th element of x
      ___
    }
    
    x[i] = value;
  }
  return x;
}

/*** R
d <- data.frame(
  x = 1:50,
  y = arma(50, 10, c(1, -0.5), c(1, -0.5), 1)
)
ggplot(d, aes(x, y)) + geom_line()
*/
編輯並執行程式碼