vendredi 29 janvier 2016

how to improve this random number generator code in c++?

I am c++ student and i am working on creating a random number generator by myself. I know about library functions but i want to make one myself. Here is the function.It just selects a possible number within a defined range. Problems are listed below. Any help would be appreciated.Please help any suggestions or tricks anything. I am making this for about 2 months.

   int rn(int lowerlt,int upperlt)
    {
/**
This function returns a random number generated using loops.
I have tried to generate a random number by taking an integer array and storing all the possible values within the defined
range in the calling part. The theory is that a variable named pointer starts getting greater and breaks the main loop
when the seed taken from system time becomes equal or greater than the pointer.

MAIN PROBLEMS:-
-The problem is that the seed which is system time is very predictable and it is very same most times which lessens the degree of randomness.
-It also takes time more than usual which is undesirable(about 10 secs).
-If range is very large then degree of randomness is very less and results are predictable.

 *But over short ranges results are very effective.
 I want to make it effective for big ranges.
**/

const int size=upperlt-lowerlt;          //Constant size of the integer array.

int ar[size];                         //Array to store all possible values within defined range.
int i,x,ret;                   //Variables to control loops and return value.
long pointer=0;     //pointer variable. The one which breaks the main loop.


//Loop to initialize the array with possible values..
for(i=0,x=lowerlt;x<=upperlt;i++,x++)
    ar[i]=x;

long seed=time(0);

//Main loop . To find the random number.
for(i=0;pointer<=seed;i++,pointer++)
{
    ret=ar[i];
    if(i==size-1)
    {
        for(;i>=0;i--)    //Reverse loop.
            {
                ret=ar[i];
            }
    }
}

return ret;     //The return statement .
}




Aucun commentaire:

Enregistrer un commentaire