集册 Java实例教程 蒙特接近PI

蒙特接近PI

欢马劈雪     最近更新时间:2020-01-02 10:19:05

493
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
通过蒙特卡洛模拟逼近PI

public class Main {

  public static void main(String[] args) {
  /*
  来 自*
   时 代 J a v a - nowjava.com
  */

    int iter = 10000000; // # iterations

    int hits = 0;

    for (int i = 0; i < iter; i++) {

      double rX = 2 * Math.random() - 1.0;

      double rY = 2 * Math.random() - 1.0;

      double dist = rX * rX + rY * rY;

      if (dist <= 1.0) // falls inside the disk

        hits++;

    }

    double ratio = (double) hits / iter; // Ratio of areas

    double area = ratio * 4.0;

    
展开阅读全文