模擬 AR(p) 模型
自我迴歸(AR)模型是一種用於時間序列的線性迴歸,預測值會依賴前幾個時間點的數值。因為有這種對過去時間點的依賴,模型必須按時間順序逐點計算。這表示需要使用 for 迴圈,因此 C++ 派得上用場!
以下是 R 的演算法:
ar1 <- function(n, constant, phi, eps) {
p <- length(phi)
x <- numeric(n)
for(i in seq(p + 1, n)) {
value <- rnorm(1, constant, eps)
for(j in seq_len(p)) {
value <- value + phi[j] * x[i - j]
}
x[i] <- value
}
x
}
n 是模擬觀測值的數量,c 是常數項,phi 是自我相關係數的數值向量,eps 是雜訊的標準差。請完成 ar2() 的定義,這是 ar1() 的 C++ 翻譯版。
本練習屬於課程
用 Rcpp 最佳化 R 程式碼
練習說明
- 使用 Rcpp 的 R API,產生一個平均數為
c、標準差為eps的常態分佈隨機數。 - 讓內層 for 迴圈從
0迭代到p。 - 在內層迴圈中,將
value增加為phi的第j個元素乘上x的「第 i 減 j 減 1」個元素。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
#include
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector ar2(int n, double c, NumericVector phi, double eps) {
int p = phi.size();
NumericVector x(n);
// Loop from p to n
for(int i = p; i < n; i++) {
// Generate a random number from the normal distribution
double value = ___::___(___, ___);
// Loop from zero to p
for(int j = ___; j < ___; j++) {
// Increase by the jth element of phi times
// the "i minus j minus 1"th element of x
value += ___[___] * ___[___];
}
x[i] = value;
}
return x;
}
/*** R
d <- data.frame(
x = 1:50,
y = ar2(50, 10, c(1, -0.5), 1)
)
ggplot(d, aes(x, y)) + geom_line()
*/