Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

HydroX

Random Range code, need comments

This topic is 5937 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I found this source code somewhere.. looks good. I would like to know if its good and any ways to improve it(faster, more random) Though you cant really random 2sets of numbers at the same time. example
cout << rand(1,10);
cout << rand(1,10);
 
will return the same thing.. anyway to fix this? thx. here is teh code
///////////////////////////////////
// Random Range number generator //
///////////////////////////////////

void init_mm();
int number_range(int from, int to);
int number_mm(void);
static int rgiState[2+55];

int Rand(int a, int b){
    	init_mm(); //seed the number generator
    	return number_range(a,b);
}
int number_mm(void){
    int *piState, iState1, iState2, iRand;
    piState= &rgiState[2];
    iState1= piState[-2];
    iState2= piState[-1];
    iRand= (piState[iState1] + piState[iState2])
    			& ((1<< 30) - 1);
    piState[iState1]= iRand;
    if (++iState1== 55)	iState1 = 0;
    if (++iState2== 55)	iState2 = 0;
    piState[-2]= iState1;
    piState[-1]= iState2;
    return iRand>> 6;
}
int number_range(int from, int to){
	int power, number;
    if ((to=to-from+1)<=1) return from;
    for (power= 2; power< to; power<<= 1);
    while ((number= number_mm() & (power- 1 )) >= to);
    return from+ number;
}

void init_mm(){
    int *piState, iState;
    piState= &rgiState[2];
    piState[-2]= 55-55;
    piState[-1]= 55-24;
    piState[0]= ((int) time( NULL )) & (( 1 << 30 )-1);
    piState[1]= 1;
    for (iState = 2; iState < 55; iState++){
        	piState[iState] = (piState[iState-1] + piState[iState-2]) & ((1<<30)-1);
    }
}
   
Edited by - HydroX on February 23, 2002 3:16:05 AM Edited by - HydroX on February 23, 2002 3:16:33 AM

Share this post


Link to post
Share on other sites
Advertisement
Looks like one of the Knuth random number algorithms, as used by thousands of MUDs. It''s probably fine. Horrible but accurate code. The reason you get the same number twice is because you must not seed the value every time you call Rand. Same goes for every pseudo random number generator. Call init_mm elsewhere, not in Rand.

[ MSVC Fixes | STL | SDL | Game AI | Sockets | C++ Faq Lite | Boost ]

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!