Generate Random numbers without using any external functions





 Typical pseudo-random number generators calculate new numbers based on previous ones, so in theory they are completely deterministic. The only randomness is guaranteed by providing a good seed (initialization of the random number generation algorithm). As long as the random numbers aren't very security critical (this would require "real" random numbers), such a recursive random number generator often satisfies the needs.

The recursive generation can be expressed without any "external" functions, once a seed was provided. There are a couple of algorithms solving this problem. A good example is the Linear Congruential Generator.




 /**
 * 
 */
package com.kartik.org;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * @author kmandal
 *
 */
public class KartikRandomNumber implements Serializable{

 private static final long serialVersionUID = 1L;


 /**
  * @param args
  */
 public static void main(String[] args) {
   System.out.println(myRand());

 }

  public static int myRand ()
  {
    int next = testSerialversionRead();
    next = ((next * next * next ) / 100 ) % 10000 ;
    testSerialversionWrite(next);
    return next ;
  }
  
  /*public static int myRand (int next)  // Generate a 4 digit pseudo-random integer
  {
   // int next = 3251 ; 
    next = ((next * next) / 100 ) % 10000 ;
    testSerialversionWrite(next);
    return next ;
  }
   
  public static int myRandInRange ( int min, int max )  // max-min must be <10000!!
  {
   int taxn=testSerialversionRead();
   
    return myRand(taxn) % (max+1-min) + min;
  }*/
  
  public static void testSerialversionWrite(int txn) {
    try{
     FileOutputStream fout = new FileOutputStream("d:\\txnsearch1.ser");
     ObjectOutputStream oos = new ObjectOutputStream(fout);   
     oos.writeObject(txn);
     oos.close();
       }catch(Exception ex){
        ex.printStackTrace();
       } 
  }
  
  
  public static int testSerialversionRead() {
   int txn = 200;
     try{

      FileInputStream fin = new FileInputStream("d:\\txnsearch1.ser");
      ObjectInputStream ois = new ObjectInputStream(fin);
      txn = (int) ois.readObject();
      ois.close();
     }catch(Exception ex){
      ex.printStackTrace(); 
     }
  return txn; 
  }
}





OutPut: 
-7418
-3455 
2515


                        

If you find this post helpful, I would really appreciate if you can share it with your friends. Also you can check more questions and analysis here.




Previous
Next Post »