Tuesday, December 3, 2013

generate random number

use Linear_congruential_generator

http://en.wikipedia.org/wiki/Linear_congruential_generator

r = a X + c

X is the initail seed. we can use the TSC value for that. And we use the current random number to generate the next random number. The parameters of a and c are form:
Sourcem(multiplier) a   (increment) coutput bits of seed in rand() / Random(L)
Numerical Recipes23216645251013904223

Here is some code I wrote:

// Generate Random Number using Linear congruential generator
/*
#define MULTIPLIER 1664525
#define INCREMENT 1013904223

// save the seed in the SMRAM
// SMM_BASE + 0xFD00
unsigned int *saved_seed = (unsigned int*)(SMM_BASE + 0xFD00);

// Get a seed from tsc
//u32 initial_seed = (u32)(get_rdtsc() >> 32);
// *saved_seed = initial_seed;

u32 rand = 0xfff & (MULTIPLIER*(*saved_seed) + INCREMENT);
*saved_seed = rand;

// printk(BIOS_DEBUG,"rand is: %x\n", rand);
// the random number is resides in [1, 0xffff]

No comments: