C++ 程式用於找出馬爾科夫鏈中給定時間中某一狀態的機率
在本文中,我們將討論一個程式,該程式用於找出在馬爾科夫鏈中從初始狀態到終止狀態在給定時間段內到達的機率。
馬爾科夫鏈是一種隨機過程,包括多個狀態以及從一個狀態到另一個狀態的關聯機率。從一個狀態移動到另一個狀態需要單位時間。
馬爾科夫鏈可以用有向圖表示。為了解決這個問題,我們可以從給定的馬爾科夫鏈中繪製一個矩陣。在該矩陣中,位於位置 (a,b) 的元素將表示從狀態“a”到狀態“b”的機率。
這將導致使用以下公式對機率分佈進行遞迴計算
P(t) = Matrix * P(t-1)
示例
#include <bits/stdc++.h>
using namespace std;
#define float_vec vector<float>
//to multiply two given matrix
vector<float_vec > multiply(vector<float_vec > A, vector<float_vec > B, int N) {
vector<float_vec > C(N, float_vec(N, 0));
for (int i = 0; i < N; ++i)
for (int j = 0; j < N; ++j)
for (int k = 0; k < N; ++k)
C[i][j] += A[i][k] * B[k][j];
return C;
}
//to calculate power of matrix
vector<float_vec > matrix_power(vector<float_vec > M, int p, int n) {
vector<float_vec > A(n, float_vec(n, 0));
for (int i = 0; i < n; ++i)
A[i][i] = 1;
while (p) {
if (p % 2)
A = multiply(A, M, n);
M = multiply(M, M, n);
p /= 2;
}
return A;
}
//to calculate probability of reaching from initial to final
float calc_prob(vector<float_vec > M, int N, int F, int S, int T) {
vector<float_vec > matrix_t = matrix_power(M, T, N);
return matrix_t[F - 1][S - 1];
}
int main() {
vector<float_vec > G{
{ 0, 0.08, 0, 0, 0, 0 },
{ 0.33, 0, 0, 0, 0, 0.62 },
{ 0, 0.06, 0, 0, 0, 0 },
{ 0.77, 0, 0.63, 0, 0, 0 },
{ 0, 0, 0, 0.65, 0, 0.38 },
{ 0, 0.85, 0.37, 0.35, 1.0, 0 }
};
//number of available states
int N = 6;
int S = 4, F = 2, T = 100;
cout << "Probability of reaching: " << F << " in time " << T << " after starting from: " << S << " is " << calc_prob(G, N, F, S, T);
return 0;
}輸出
Probability of reaching: 2 in time 100 after starting from: 4 is 0.271464
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP