Advertisement
Guest User

Montecarlo

a guest
Jul 22nd, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.43 KB | None | 0 0
  1.  
  2. public class Montecarlo {
  3.    
  4.     private static int FALLIDO = 0;
  5.     private static int SIN_FALLA = 1;
  6.     private static int MAX_TIRADAS = 9999999;
  7.     private static double EPSILON = 0.000001;
  8.     private int fallidos = 5;
  9.     private int sin_fallas = 5;
  10.     private int totales = 10;
  11.  
  12.     public Montecarlo() {}
  13.    
  14.     public double getProbability(){
  15.          int exitos = 0;
  16.          int tiradas = 0;
  17.          double prob_ant = -1;
  18.          double prob_act = 0;
  19.          while(!converge(prob_ant,prob_act,tiradas)) {
  20.              int p1 = getProduct();
  21.              int p2 = getProduct();
  22.              int p3 = getProduct();
  23.             if ( (p1 == FALLIDO) && (p2 == FALLIDO ) && (p3 == FALLIDO) )
  24.                  exitos ++;
  25.             tiradas ++;
  26.             prob_ant = prob_act;
  27.             prob_act = (double) exitos/tiradas;
  28.             resetValues();
  29.          }
  30.  
  31.         return prob_act;
  32.     }
  33.    
  34.     private void resetValues() {
  35.         fallidos = 5;
  36.         sin_fallas = 5;
  37.         totales = 10;
  38.     }
  39.  
  40.     private int getProduct(){
  41.         double fallas =(double) fallidos / totales;
  42.         double[] prob_acum = {fallas,1.0F};
  43.         double r = Math.random();
  44.        
  45.         for(int i = 0; i < prob_acum.length;i++) {
  46.            
  47.             if (r < prob_acum[i] && i == FALLIDO ) {
  48.                 totales --;
  49.                 fallidos--;
  50.                 return i;
  51.             }
  52.             else if(r < prob_acum[i] && i == SIN_FALLA ) {
  53.                 totales --;
  54.                 sin_fallas--;
  55.                 return i;
  56.             }
  57.         }
  58.         return -1;
  59.     }
  60.    
  61.     boolean converge( double ant, double  act, int tiradas) {
  62.         if((Math.abs(ant- act) < EPSILON) && tiradas > MAX_TIRADAS)
  63.             return true;
  64.         return false;
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement