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.

RANDOM SEQUENCE GENERATOR

Status
Not open for further replies.

embeddedlover

Full Member level 5
Joined
Aug 10, 2007
Messages
277
Helped
46
Reputation
92
Reaction score
38
Trophy points
1,308
Activity points
3,155
#include<stdio.h>
#include<stdlib.h>
main()
{
int x = rand() % 25;
printf("%d",x);
}

I am using rand() function and it always gives me a output of 16.
Please give me the reason.

As per my knowledge a rand() generates random number based on system clock. But if i load to micro controller on what basis is it generating a random number?
 

Well.
In one of my application which use avr-libc, there is also have this problem. Every first time, rand() will generate the same value. But next, the value is different.
And I see the code:
static unsigned long next = 1;

ATTRIBUTE_CLIB_SECTION
int
rand(void)
{
return do_rand(&next);
}

ATTRIBUTE_CLIB_SECTION
static int
do_rand(unsigned long *ctx)
{
#ifdef USE_WEAK_SEEDING
/*
* Historic implementation compatibility.
* The random sequences do not vary much with the seed,
* even with overflowing.
*/
return ((*ctx = *ctx * 1103515245L + 12345L) %
((unsigned long)RAND_MAX + 1));
#else /* !USE_WEAK_SEEDING */
/*
* Compute x = (7^5 * x) mod (2^31 - 1)
* wihout overflowing 31 bits:
* (2^31 - 1) = 127773 * (7^5) + 2836
* From "Random number generators: good ones are hard to find",
* Park and Miller, Communications of the ACM, vol. 31, no. 10,
* October 1988, p. 1195.
*/
long hi, lo, x;

x = *ctx;
/* Can't be initialized with 0, so use another value. */
if (x == 0)
x = 123459876L;
hi = x / 127773L;
lo = x % 127773L;
x = 16807L * lo - 2836L * hi;
if (x < 0)
x += 0x7fffffffL;
return ((*ctx = x) % ((unsigned long)RAND_MAX + 1));
#endif /* !USE_WEAK_SEEDING */
}

Then you see, every first time, rand() initialize value is 1. So you can't get different value in first time.

I think you maybe do this to improve it:
1.Write rand by yourselft. Haha, this may be difficult.
2.Drop fist several value of rand(). The several number is must different every time.
 

does rand() work for micro controllers or not?
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top