三、时齐马氏链实际应用

1.题目一

（赌徒的破产或称带吸收壁的随机游动）系统的状态是0~n，反映赌博期间拥有的金钱数额，当他输光或拥有钱数为n时，赌博停止，否则他将持续赌博。每次以概率p赢得1，以概率q = 1-p输掉1。

实验测试

``````#include<iostream>
using namespace std;
double b[100][100];//设置为全局数组。

double markov(double a[100][100], double c[100][100], int n) {
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= n; j++) {
for (int k = 0; k <= n; k++) {
c[i][j] += b[i][k] * a[k][j];
}
}
}
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= n; j++) {
b[i][j] = c[i][j];
}
}
return 1;
}

int main() {
double a[100][100] = {0};//设置为局部矩阵
double c[100][100] = {0};
int n;
double p;
int s,k;
cout << "请输入n(赌徒输光或者拥有钱数为n的时候就结束)";
cin >> n;
cout << "请输入概率p（为赌徒以概率p赢得1元） : ";
cin >> p;
cout << "请输入s（s为赌徒初始的赌金）";
cin >> s;
cout << "请输入k（为你想看到他k次就输光）";
cin >> k;
//初始化一个初值为0的矩阵
//初始化一步转移矩阵
a[0][0] = 1, a[n][n] = 1;
for (int i = 1; i < n; i++) {
a[i][i - 1] = p;
a[i][i + 1] = 1 - p;
}
//初始化迭代矩阵
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= n; j++) {
b[i][j] = a[i][j];
}
}
//打印输出
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= n; j++) {
printf("%.6f  ", a[i][j]);
}
cout << endl;
}
cout << endl;
//迭代计算,k为赌徒赌的次数
while(k>1){
markov( a, c,n);
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= n; j++) {
c[i][j] = 0;
}
}
k--;
}
//打印结果矩阵
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= n; j++) {
printf("%.6f  ", b[i][j]);
}
cout << endl;
}
cout << b[s][0];
}
``````

操作使用教程

矩阵维数的调整

``````
```cpp
double b[100][100];//设置为全局数组。可以修改这里来扩展矩阵的维数

double markov(double a[100][100], double c[100][100], int n) {
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= n; j++) {
for (int k = 0; k <= n; k++) {
c[i][j] += b[i][k] * a[k][j];
}
}
}
``````

数据的输入

``````
cout << "请输入n(赌徒输光或者拥有钱数为n的时候就结束)";
cin >> n;
cout << "请输入概率p（为赌徒以概率p赢得1元） : ";
cin >> p;
cout << "请输入s（s为赌徒初始的赌金）";
cin >> s;
cout << "请输入k（为你想看到他k次就输光）";
cin >> k;
``````

THE END

)">