概率算法

作者: FORGET_静哥哥 | 来源:发表于2019-02-15 09:31 被阅读0次
    
    
    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);
          }
    }
    
    

    相关文章

      网友评论

        本文标题:概率算法

        本文链接:https://www.haomeiwen.com/subject/inzueqtx.html