基本演算法思想-概率演算法
阿新 • • 發佈:2019-01-14
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); } }