이 글에서는 Markov chain에서 주어진 시간 안에 초기 상태에서 최종 상태에 도달할 확률을 구하는 프로그램에 대해 논의할 것입니다.
마르코프 체인은 다양한 상태와 한 상태에서 다른 상태로 이동할 관련 확률로 구성된 무작위 프로세스입니다. 한 상태에서 다른 상태로 이동하는 데 단위 시간이 걸립니다.
Markov Chain은 방향 그래프로 나타낼 수 있습니다. 문제를 해결하기 위해 주어진 마르코프 체인에서 행렬을 만들 수 있습니다. 해당 행렬에서 (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