代码证明内特朗箱子悖论

代码证明内特朗箱子悖论_第1张图片

图片来自知乎https://www.zhihu.com/question/26435542/answer/112876996?utm_source=wechat_session&utm_medium=social&utm_oi=855348107909664768

import java.util.LinkedList;

public class boxQuestion {
	public static void main(String[] args) {
		float num1 = 0;
		float num2 = 0;
		test(num1,num2);
		
		}
	public static void test(float num1,float num2) {
		for(int i = 0; i < 10000;i ++) {
		LinkedList list =new LinkedList();
		boxFirst b1 = new boxFirst();
		boxSecond b2 = new boxSecond();
		boxThird b3 = new boxThird();
//		System.out.println(b1.box);
//		System.out.println(b2.box);
//		System.out.println(b3.box);
		list.add(b1.box);list.add(b2.box);list.add(b3.box);
//		System.out.println(list);
		LinkedList boxChoose = (LinkedList) list.get((int) (Math.random() * 3));
//		System.out.println(boxChoose);
		int temp = (int) (Math.random() * 2);
		String str1 = (String) boxChoose.get(temp);
//		System.out.println(str1);
		boxChoose.remove(temp);
		String str2 = (String) boxChoose.pop();
//		System.out.println(str2);
		String Regex = "red";
//		System.out.println(str1.matches("red+[1-3]"));
		if(str1.matches("red+[1-3]") == true){
			num1 ++;
			if(str2.matches("red+[1-3]")) {
			num2 ++;
			}	
		}
	}
		System.out.println("100000中第一个是红球的次数:" + num1);
		System.out.println("100000中在第一个是红球的概率下第二个也是红球的次数:" + num2);
		float answer = num2/num1;
		System.out.println("结果是:" + answer);
	}
		
	public static class boxFirst{
		LinkedList box =new LinkedList();
		public boxFirst() {
			box.add("red1");
			box.add("red2");
		}
	}
	public static class boxSecond{
		LinkedList box =new LinkedList();
		public boxSecond(){
			box.add("red3");
			box.add("blue3");
		}
	}
	public static class boxThird{
		LinkedList box =new LinkedList();
		public boxThird(){
			box.add("blue1");
			box.add("blue2");
		}
	}
	
} 
  

运行结果

100000中第一个是红球的次数:49759.0
100000中在第一个是红球的概率下第二个也是红球的次数:33169.0
结果是:0.66659296
100000中第一个是红球的次数:50210.0
100000中在第一个是红球的概率下第二个也是红球的次数:33525.0
结果是:0.6676957
100000中第一个是红球的次数:49834.0
100000中在第一个是红球的概率下第二个也是红球的次数:33488.0
结果是:0.671991

 

你可能感兴趣的:(Java)