蒙特卡罗方法于20世纪40年代美国在第二次世界大战中研制原子弹的“曼哈顿计划”计划的成员S.M.乌拉姆和J.冯·诺伊曼首先提出。数学家冯·诺伊曼用驰名世界的赌城—摩纳哥的Monte Carlo—来命名这种方法,为它蒙上了一层
神秘色彩。在这之前,蒙特卡罗方法就已经存在。1777年,法国数学家布丰(Georges Louis Leclere de Buffon,1707—1788)提出用投针实验的方法求圆周率π。这被认为是蒙特卡罗方法的起源。
public class MontePI { /** * @param args */ public static void main(String[] args) { System.out.println("Please input times: "); Scanner sc=new Scanner(System.in); caculatePI(sc.nextInt()); }
public static void caculatePI(int countInSquarel) { int countInCircle = 0, i, resulttimes; double x, y; /* 坐标 */ Random s = new Random(); for (resulttimes = 0; resulttimes < 10; resulttimes++) { /* 输出十次结果 */ for (i = 1; i <= countInSquarel; i++) { x = s.nextDouble(); /* 在0~1之间产生一个随机x坐标 */ y = s.nextDouble(); /* 在0~1之间产生一个随机y坐标 */ if (caculateAcreage(x,y)<= 1.0) countInCircle++; /* 统计落入单位圆中的点数 */ } System.out.println("The result of pai is " + (double) countInCircle * 4 / countInSquarel); /* 计算出π的值 */ countInCircle = 0; } }