zinch

Monte Carlo Simulation with Stream API

Sep 22nd, 2017
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.76 KB | None | 0 0
  1. import java.util.function.*;
  2. import java.util.stream.*;
  3. import static java.util.stream.Collectors.*;
  4. import java.util.*;
  5.  
  6. public class MonteCarlo{
  7.  
  8.     private final static int N = 10_000_000;
  9.     private final static Random  r = new Random();
  10.    
  11.     public static Map<Integer, Double> parallelDiceRolls() {
  12.        
  13.         double fraction = 1.0 / N;
  14.        
  15.         return IntStream.range(0, N)
  16.             .parallel()
  17.             .mapToObj(n -> twoDiceThrows())
  18.             .collect(groupingBy(side -> side, summingDouble(n -> fraction)));
  19.     }
  20.    
  21.     public static int twoDiceThrows() {
  22.         return r.nextInt(6) + r.nextInt(6) + 2;
  23.     }
  24.    
  25.     public static void main(String []args){
  26.         System.out.println(parallelDiceRolls());
  27.     }
  28. }
Add Comment
Please, Sign In to add comment