概率算法
2019-02-15 本文已影响0人
FORGET_静哥哥
package com.xj.www.algo;
import java.util.Scanner;
/**
* 概率算法
*
* @author xiongjing
*
*/
public class ProbabilityTest {
// 蒙特卡罗算法
static double MontePI(int n) {
double PI, x, y;
int i, sum;
sum = 0;
for (i = 1; i < n; i++) {
x = Math.random();
y = Math.random();
if ((x * x + y * y) <= 1) {
sum++;
}
}
PI = 4.0 * sum / n;
return PI;
}
// 程序主入口
public static void main(String[] args) {
int n;
double PI;
System.out.println("蒙特卡罗概率算法计算π值:");
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.println("输入点的数量:");
n = sc.nextInt();
PI = MontePI(n);
System.out.println("PI=" + PI);
}
}