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

  1.  
  2. package simula.random;
  3.  
  4. /**
  5. ** Implements a Linear Congruential Generator (LCG)
  6. ** This is a toy generator and we don't recommend it for serious uses
  7. ** This is based on the following:
  8. **      <p>
  9. **    <center>
  10. **        <em>I<sub>j+1</sub></em> = (<em>I<sub>j</sub></em> ╫ 1103515245 + 12345) & 0x7FFFFFFF
  11. **    </center>
  12. **    <p>
  13. */
  14.  
  15. public class RandomEngineLCG extends RandomEngine {
  16. /**
  17. ** Generator state in bytes generations
  18. */    
  19.     private long state;
  20.     
  21.  
  22.     //  Constructors
  23.  
  24. /**
  25. ** Creates a new engine with current time used as the seed
  26. */
  27.     public RandomEngineLCG() {
  28.         this.setSeed(System.currentTimeMillis());
  29.     }
  30. /**
  31. ** Creates an new engine with given seed
  32. ** @param seed generator seed
  33. */
  34.     public RandomEngineLCG(long seed) {
  35.         this.setSeed(seed);
  36.     }
  37. /**
  38. ** Returns the next pseudoRandom byte
  39. ** @return the next byte from the generator.
  40. */
  41.     public byte nextByte() {
  42. // Higher bits are better 
  43. // No buuffering in this engine. Everytime all bits are generated 
  44.         state = (state * 1103515245L + 12345L) & 0x7FFFFFFFL;
  45.         return (byte) ((state >> 11) & 0xFF);
  46.     }
  47.     // Seeds check
  48.  
  49. /**
  50. ** Resets the generator seed
  51. ** @param seed generator seed
  52. */
  53.     public void setSeed(long seed) {
  54.         super.setSeed();              // notifies to parent class this change 
  55.         state = seed & 0xFFFFFFFFL;
  56.     }
  57. }