Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

how to generate random numbers using C-langugae?

Status
Not open for further replies.

Delta11

Junior Member level 3
Joined
May 14, 2009
Messages
25
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Activity points
1,454
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
 

    Delta11

    Points: 2
    Helpful Answer Positive Rating
Random number generation

take an array and enter no's in it

Added after 1 minutes:

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.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top