蒙特卡洛法-随机行走

  • 一、模型介绍
  • 二、具体代码
  • (一)算法流程图
  • (二)代码
  • 三、结果分析
  • 四、写在最后


一、模型介绍

  • 蒙特卡洛方法
    当所求问题的解是某个事件的概率,或者是某个随机变量的数学期望,或者是与之有关的量时,通过某种试验的方法,得出该事件发生的频率,再通过它得到问题的解。这就是蒙特卡罗方法的基本思想。蒙特卡罗方法的关键步骤在于随机数的产生,计算机产生的随机数都不是真正的随机数(由算法确定的缘故),如果伪随机数能够通过一系列统计检验,我们也可以将其当作真正的随机数使用。
  • 基于蒙特卡洛法的随机行走
    随机游走(random walk)也称随机漫步,随机行走等是指基于过去的表现,无法预测将来的发展步骤和方向。核心概念是指任何无规则行走者所带的守恒量都各自对应着一个扩散运输定律 ,接近于布朗运动,是布朗运动理想的数学状态,现阶段主要应用于互联网链接分析及金融股票市场中。

二、具体代码

(一)算法流程图


python 蒙特卡洛 卡牌概率 蒙特卡洛方法随机数_python 蒙特卡洛 卡牌概率

(二)代码

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

#define big 200

void put(FILE *outstream, double data1, double data2)
{
	fprintf(outstream, "%f,%f\n,", data1, data2);
}
void init(int *p, long size)
{
	int *q = p;
	while(q<(p+size))
	{
		*q = 0;
		q++;
	}
	*(q-size/2+big/2) = 1;
}
//随机行走 
void walk(int *x, int *y, int s)
{
	int step = rand() % 8;
	int p1 = *x-1;
	int p2 = *x+1;
	int s1 = *y-1;
	int s2 = *y+1;
	if(*x==0)
		p1 = s-1; 
	else if(*x==s-1)
		p2 = 0;
	
	if(*y==0)
		s1 = s-1; 
	else if(*y==s-1)
		s2 = 0;
		
	switch(step)
	{
	case 0:
		*x = p2;//+
		break;
	case 1:
		*x = p1;//-
		break;
	case 2:
		*y = s2;//+
		break;
	case 3:
		*y = s1;//-
		break;
	case 4:
		*x = p2; *y = s2;//++
		break;
	case 5:
		*x = p1; *y = s1;//--
		break;
	case 6:
		*x = p2; *y = s1;//+-
		break;
	case 7:
		*x = p1; *y = s2;//-+
		break;
	default:
		printf("运行错误!");
		break;
	}
}
//判断是否靠近
bool judge(int x, int y, int space[][big], int s)
{
	int p1 = x-1;
	int p2 = x+1;
	int s1 = y-1;
	int s2 = y+1;
	if(x==0)
		p1 = s-1; //19
	else if(x==s-1)
		p2 = 0;
	
	if(y==0)
		s1 = s-1; 
	else if(y==s-1)
		s2 = 0;
		
	if(space[p2][y]==1) return true;
	if(space[p1][y]==1) return true;
	if(space[x][s2]==1) return true;
	if(space[x][s1]==1) return true;
	if(space[p2][s2]==1) return true;
	if(space[p2][s1]==1) return true;
	if(space[p1][s2]==1) return true;
	if(space[p1][s1]==1) return true;
	
	return false;
}
void DLA(int width, int space[][big])
{
	int i;
	for(i=0; i<3000; i++)
	{
		//生成随机点
		int x = rand()% width;//0-19
		int y = rand()% width;
		if(space[x][y]==1) continue;
		while(!judge(x,y,space,width))
		{
			walk(&x, &y, width);
		}
		space[x][y] = 1;
	}
}
int main(int argc, char *argv[])
{
	int space[big][big];
	long size = sizeof(space)/4;//元素个数 
	int width = sqrt(size);
	
	init(*space,size);
	
	DLA(width,space);
	
	//***********************************
 	FILE *outstream;
	if((outstream=fopen("hahaha.dat", "ab")) == NULL)
	{
		printf("Cannot open file, press any key to exit!\n");
		exit(1);
	}
 	//************************************/
 	int m, n;
	for(m=0; m<width; m++)
	{
		for(n=0; n<width; n++)
		{
			if(space[m][n]==1) put(outstream,m*1.0,n*1.0);
			printf("%d\t",space[m][n]);
		}
	}
	fclose(outstream);
	return 0;
}

三、结果分析


python 蒙特卡洛 卡牌概率 蒙特卡洛方法随机数_蒙特卡洛_02

四、写在最后

  • 编程过程中点阵的数目不宜过大或过小,过大计算时间长,过短无法体现明显现象。
  • 关于DLA的一些其他扩散和聚集领域应用。本次测试只是为了体现随机行走的基本思想,该思想在其他领域的研究应用也非常广泛。例如:P2P 搜索中Random Walk 搜索方法搜索信息的扩散;在高分子中,高分子的形状类似于无规则行走,以及在金融等其他领域。