提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
通过蒙特卡洛模拟逼近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;