mercredi 31 mars 2021

Implementation of Random subclass in Java with a linear congruential generator

I am writing my own Random subclass in java that I want another program to inherit. The subclass should consist of the two constructors Random()which should create a new number generator and Random(long seed) which should create a new random number generator using a single long seed. It should also contain the methods: int next(int bits) which should generate the next pseudo-random number and void setSeed(long seed) which should set the seed of the random number generator.

The seed is retrieved from the user but when I run the program with different types of seeds it outputs the same sequence of numbers despite the change of the seed. I wonder if it might have something to do with my next()method. Could someone see if there is anything I am missing and if so what I should add/remove?

Random() {

  this(System.currentTimeMillis());

}

Random(long seed) {

  
  this.setSeed(seed);

)

//I have defined a, b and m as constants 

int next(int bits) {
  x = ((a * x + b) % m);
  return (int)(x >>> (48 - bits));

}

void setSeed(long seed) {

  x = (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1);

}



Aucun commentaire:

Enregistrer un commentaire