home *** CD-ROM | disk | FTP | other *** search
/ io Programmo 21 / IOPROG_21.ISO / SOFT / JSL.ZIP / JSL20 / simula / random / Uniform.java < prev    next >
Encoding:
Java Source  |  1998-02-20  |  1.7 KB  |  85 lines

  1.  
  2. package simula.random;
  3.  
  4. import java.util.Random;
  5.  
  6. /**
  7. ** The class Uniform inherits from Generator and is useful to draw numbers with
  8. ** uniform probability in the real segment [a,b].
  9. */
  10. public class Uniform extends Generator
  11. {
  12. /**
  13. ** segment lower bound.
  14. */  
  15.   private double a;
  16.   
  17. /**
  18. ** segment upper bound
  19. */  
  20.   private double b;
  21.   
  22.  
  23. /**
  24. ** @param a    segment lower bound
  25. ** @param b    segment upper bound
  26. */
  27.   public Uniform(double a,double b)
  28.   {
  29.     random = new RandomEngineJava();
  30.     setParam(a,b);
  31.   }  
  32. /**
  33. ** @param seed seed for the Java Random generator
  34. ** @param a    segment lower bound
  35. ** @param b    segment upper bound
  36. */  
  37.   public Uniform(long seed,double a,double b)
  38.   {
  39.     random = new RandomEngineJava(seed);
  40.     setParam(a,b);
  41.   }  
  42. /**
  43. ** @param e    Random Generator Engine instance
  44. ** @param a    segment lower bound
  45. ** @param b    segment upper bound
  46. */
  47.   public Uniform(RandomEngine e,double a,double b)
  48.   {
  49.     random = e;
  50.     setParam(a,b);
  51.   }  
  52. /**
  53. ** Return the value of the density in the given point
  54. ** @param x   point to sample for density
  55. */
  56.   public double density (double x)
  57.   {
  58.     double res=0;  
  59.  
  60.     if ((x>=a) & (x<=b))
  61.       res=1/(b-a);
  62.     return res;
  63.   }  
  64. /**
  65. ** Draws a value with a uniform probability in real segment [a,b]
  66. ** @return an instance of Value containing a real point. 
  67. ** @see Value
  68. */ 
  69.   public Value draw()
  70.   {
  71.     return new RealValue( random.nextDouble() * (b-a) + a);
  72.   }  
  73. /**
  74. ** Resets generator parameters (reordered if a > b)
  75. **/
  76.   public void setParam(double a,double b)
  77.   {
  78.     this.a = a<=b ? a : b;
  79.     this.b = a<=b ? b : a;
  80.   }  
  81.   public int type()
  82.   {
  83.       return REAL_TYPE;
  84.   }  
  85. }