Page 1 of 1

in search of a good random number generator

Posted: Wed May 05, 2004 8:44 am
by jack
i been searching the web for a good random number generator, i found one by Paul Dixon. http://www.masmforum.com/viewtopic.php?t=2740
i dapted it to PellesC, but need some help since i am still a C neophyte.
how can i optionally set the static variable rng? (to seed the rnd generator)

Code: Select all

double random(void)
{	static long long int rng=0x1954678542154787;
	int result;
	long long int mask2=0x7fffffffffffffff;
	_asm{
		movq mm0,rng;		//get the last number 
		movq mm1,mm0; 
		psllq mm0,1; 
		pxor mm1,mm0; 
		pand mm1,mask2; 
		movq mm0,mm1; 
		psrlq mm1,62; 
		pxor mm0,mm1; 
		movq rng,mm0;
		emms;			//re-enable FPU
	}
	return frexp((double) rng,&result);              //result between 0 and 1
}

Posted: Wed May 05, 2004 10:10 am
by blueznl
why don't you use the build in commands, or are they not fast enough?

x = random(n)

Posted: Wed May 05, 2004 10:15 am
by jack
my quest is for a 64 bit random number generator, to be included in a lib. :)

Posted: Wed May 05, 2004 10:16 am
by LarsG
maybe he's trying to do his own, or just understanding how it works?!?
Anyways.. I seem to recall there was some talk about this on the forum some time ago.. Perhaps you can find something if you search?!

Posted: Wed May 05, 2004 10:58 am
by Road Runner
Jack,
the code you posted is a 63 bit generator, for the 64 bit version see:
http://masmforum.com/viewtopic.php?t=2740&start=21 where it says "new version:"

Posted: Wed May 05, 2004 11:24 am
by dell_jockey
you might also want to google the net for 'Mersenne'. I'm working on that one for PB. Progress is slow, though....

Posted: Wed May 05, 2004 11:51 am
by jack
i think i got it solved, BTW which is better, numbers between 0 and 1 or -1 and 1.?
here's another, by MichaelW and Paul Dixon.

Code: Select all

#include <time.h>
#include <math.h>

double random2(void)
{	time_t t;
	static int first_time=0;
	static long long int shiftreg;//=0x1954678542154787;
	long long int mask=0x6fffffffffffffff;
	int temp;
	if (first_time==0)
		{
		first_time=1;
      time(&t)
		shiftreg=t;
		}
	_asm{
		movq mm0,shiftreg		//get the last number 
		movq mm1,mm0			//take a copy 
		psrlq mm1,1			//do 1st tap bit (LSBs) 
		pxor mm0,mm1 
		psrlq mm1,2			//do 2nd tap bit (LSBs) 
		pxor mm0,mm1 
		psrlq mm1,1 
		pxor mm0,mm1			//do 3rd tap bit (LSBs), low 60 bits now done 
                					//now correct for the high 4 bits 
		movq mm1,mm0    		//take a copy 
		psllq mm1,60    			//correct 3rd tap MSBs 
		pxor mm0,mm1 
		psllq mm1,1     			//correct 2nd tap MSBs 
		pxor mm0,mm1 
		psllq mm1,2 
		pxor mm0,mm1    		//correct 1st tap MSBs, all done 
		pxor mm0,mask
		movq shiftreg,mm0  		//write back the result 
		emms          			//re-enable FPU 
	}
	return frexp((double) shiftreg,&temp);
}
all i added is the 'frexp' to extract the mantissa.