基本算法思想-概率算法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xj80231314/article/details/86212489


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);
      }
}

猜你喜欢

转载自blog.csdn.net/xj80231314/article/details/86212489