Advertisement
vencinachev

MonteCarloPI - Java

Apr 23rd, 2021
1,210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.54 KB | None | 0 0
  1. public class Program {
  2.     static double monteCarloPI(int n) {
  3.         int pointsIn = 0;
  4.         for (int i = 0; i < n; i++) {
  5.             double x = Math.random();
  6.             double y = Math.random();
  7.             if (Math.sqrt(x*x + y*y) < 1.0) {
  8.                 pointsIn++;
  9.             }
  10.         }
  11.         return 4.0 * (double)pointsIn / n; // PI
  12.     }  
  13.     public static void main(String[] args) {
  14.         System.out.println("PI = " + monteCarloPI(100));
  15.         System.out.println("PI = " + monteCarloPI(1000));
  16.         System.out.println("PI = " + monteCarloPI(10000));
  17.         System.out.println("PI = " + monteCarloPI(10000000));
  18.     }
  19. }
  20.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement