java - 蒙特卡洛森林研究
问题描述
我有这个问题“森林由 1,200 棵树组成,形成一个完美的 40×30 矩形。左上角的树着火了。风从西边吹来,因此,任何一棵树从燃烧的左边邻居那里着火的概率是 0.85 . 立即从右侧、上方或下方的树木着火的概率都等于 0.35。”
一个。进行蒙特卡洛研究以估计超过 40% 的森林最终将被燃烧的概率。概率为 0.95,您的答案与真实值的差异不应超过 0.005
我正在用 Java 编程,我知道要获得帮助我需要自己尝试,所以请解释一下我的程序
import java.util.*;
public class MonteCarlo {
String [][] Forest = new String [30][40];
boolean moreBurn;
public void setForest(){
for(int i = 0; i < 30; i++){
for(int j = 0; j < 40; j++){
Forest[i][j] = "";
}
}
Forest[0][0] = "Burning";
}
public void Forest(){
moreBurn = false;
for(int i = 0; i < 30; i++){
for(int j = 0; j < 40; j++){
if(Forest[i][j].equals("Burning")){
if(j + 1 < 40 && Forest[i][j + 1].equals("")){
if(((int) (Math.random() * 100) + 1) <= 35){
Forest[i][j + 1] = "BurningNew";
moreBurn = true;
}
}
if(j - 1 > 0 && Forest[i][j - 1].equals("")){
if(((int) (Math.random() * 100) + 1) <= 85){
Forest[i][j - 1] = "BurningNew";
moreBurn = true;
}
}
if(i - 1 > 0 && Forest[i - 1][j].equals("")){
if(((int) (Math.random() * 100) + 1) <= 35){
Forest[i - 1][j] = "BurningNew";
moreBurn = true;
}
}
if(i + 1 < 30 && Forest[i + 1][j].equals("")){
if(((int) (Math.random() * 100) + 1) <= 35){
Forest[i + 1][j] = "BurningNew";
moreBurn = true;
}
}
}
}
}
for(int i = 0; i < 30; i++){
for(int j = 0; j < 40; j++){
if(Forest[i][j].equals("Burning")){
Forest[i][j] = "Burned";
}
if(Forest[i][j].equals("BurningNew")){
Forest[i][j] = "Burning";
}
}
}
if(moreBurn = true){
Forest();
}
}
public void printForest(){
for(int i = 0; i < 30; i++){
System.out.println(Arrays.toString(Forest[i]));
}
}
public static void main (String [] args){
MonteCarlo example = new MonteCarlo();
example.setForest();
example.Forest();
example.printForest();
}
}
所以让我解释一下我的一段代码以及我是如何开发它的。setForest() 只是让森林除了左上角之外是空白的,它正在燃烧。然后 Forest 的前两个 for 循环将相邻的树设置为 BurningNew。最初我将它设置为正在燃烧,但问题是由于我的循环,它会在第一次尝试燃烧时填充多个正确的树。我希望它一次检查一件。所以它设置为 BurningNew。然后,它将 BurningNew 设置为 Burning 并将 Burning 设置为 Burned。所以基本上一次一棵树。所以我想我会做一个布尔值并将其设置为 false,除非其中一个 if 语句为真。因此,我的递归方法只有在树着火时才有效。好吧,我一直在 0.25 左右,所以有人知道这个问题吗?
解决方案
推荐阅读
- django - 如何将现有的 django 数据库用于另一个项目
- nginx - nginx:提供不同反向代理应用程序的静态文件
- sql-server - 如何在 vb.net 睡眠期间在后台运行 .Gif 图像
- php - 根据值跳过导入行
- javascript - 基于for循环添加div类
- php - 测试数据库中是否存在数字,如果存在则创建新的
- powershell - 用于 PowerShell 功能的自定义 -PassThru 开关
- hyperledger-fabric - 以太坊 vs Hyperledger Fabric
- redis - Redis active - 跨数据中心/Kubernetes 集群的主动复制
- random - 如何使用 Numba xoroshiro128p 创建简单的随机数组