C ++程序查找马尔可夫链中给定时间的状态概率
在本文中,我们将讨论一个程序,以查找在马尔可夫链中给定时间段内从初始状态到达最终状态的概率。
马尔可夫链是一个随机过程,包括各种状态以及从一个状态到另一状态的关联概率。从一种状态转换到另一种状态需要花费单位时间。
马尔可夫链可以用有向图表示。为了解决这个问题,我们可以从给定的马尔可夫链中得出一个矩阵。在该矩阵中,位置(a,b)处的元素将表示从状态'a'进入状态'b'的概率。
这将使用公式来递归地处理概率分布
P(t) = Matrix * P(t-1)
示例
#include <bits/stdc++.h>
using namespace std;
#define float_vec vector<float>
//将两个给定矩阵相乘
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;
}
//计算矩阵的功效
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;
}
//计算从初始到最终到达的可能性
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 }
};
//可用状态数
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