Continue to Site

# how to generate random numbers using C-langugae?

Status
Not open for further replies.

#### Delta11

##### Junior Member level 3
Random number generation

Guys...... I need to get an idea how to generate random numbers using C-langugae? Would it be possible to implement such a thing efficiently using moderate microcontrollers like PIC or AVR series!

Random number generation

Hi Delta11,

Look for "linear congruential method".
This is one of the most common and simple methods for generating random numbers with uniform distribution.
Regards

Z

Points: 2

### Delta11

Points: 2
Random number generation

take an array and enter no's in it

or use pointers and give address with increment of 2.

Re: Random number generation

Use the following code for a linear congruential generater. It uses a 32-bit global unsigned integer. It must be 32 bits! For the PIC C18 compiler you can use unsigned long. You can set the seed with setSeed(seed) and get a random number with rand().

Code:
unsigned long x;

void setSeed(unsigned long seed) {
x=seed;
}

unsigned long rand() {
x = 1103515245 * x + 12345;
return x & 0x3FFFFFFF;
}

Slorn
--
dwengo... gets you started with microcontrollers!

Random number generation

OK.
Take into account that the above code generates uniformly distributed numbers in the range [0, 0x3FFF] (14 bits).
Regards

Z

Re: Random number generation

Hi zorro

That was a mistake. It should have been 0x3FFFFFFF (30-bits). I changed the code above. The code implements the gcc random generator.

If you want a smaller range just take as little bits as you need. E.g. if you need 8 bit random numbers use 0x000000FF.

Slorn
--
dwengo... gets you started with microcontrollers!

Re: Random number generation

Hi

Use your A/D converter as a source for producing random number(seed) by connecting one of the A/D input via a resistor to GND and read the result without filter or summing

All the best

Bobi

The microcontroller specialist

Status
Not open for further replies.