View previous topic :: View next topic |
Author |
Message |
JerryR
Joined: 07 Feb 2008 Posts: 167
|
Generating random number 4-255 |
Posted: Thu Oct 15, 2020 9:06 am |
|
|
This should be easy, but why do I get randx = 4 always? Thanks
Chip PIC16F1519 PCWH 5.093
Code: |
#define RAND_MAX 255
int8 Set_Identification(void)
{
int8 randx;
srand(0x55);
while (randx <= 3)
randx = rand();
return(randx);
}
|
|
|
|
temtronic
Joined: 01 Jul 2010 Posts: 9229 Location: Greensville,Ontario
|
|
Posted: Thu Oct 15, 2020 9:28 am |
|
|
not a complete program, but did you include 'STDLIB.h' ?? |
|
|
JerryR
Joined: 07 Feb 2008 Posts: 167
|
|
Posted: Thu Oct 15, 2020 9:33 am |
|
|
Yes, included that library. randx does generate a random number, but I just want to exclude numbers 0 through 3. It's the simple stuff that gets me.
Thanks for your reply! |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19520
|
|
Posted: Thu Oct 15, 2020 9:58 am |
|
|
You will.
This is a _pseudo random number generator_. It generates a sequence
of numbers, that will always be the same, if the seed (fed in by srand),
is the same. So with srand set to 55, the first number you get is 4.
This is why your result is always the same.
To generate your 4 to 255, you need to set RAND_MAX to 251, then
add 4 to the result. This then gives you 252 values from 4 to 255.
To make the first number different, you have to change the seed value
fed to srand. This is why doing something like using the value from a
RTC to generate this seed is a typical way to make the sequence hard
to predict. |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
Re: Generating random number 4-255 |
Posted: Thu Oct 15, 2020 10:00 am |
|
|
srand() initializes the randomizer. Remove the line in bold below and
move it to the start of main().
JerryR wrote: |
#define RAND_MAX 255
int8 Set_Identification(void)
{
int8 randx;
srand(0x55);
while (randx <= 3)
randx = rand();
return(randx);
}
|
|
|
|
JerryR
Joined: 07 Feb 2008 Posts: 167
|
|
Posted: Thu Oct 15, 2020 10:16 am |
|
|
Thanks PCM !! |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19520
|
|
Posted: Thu Oct 15, 2020 10:29 am |
|
|
and (of course), ideally set it with something that is really hard to predict.
A RTC, a count while a capacitor charges, a value fed in from something
external etc. etc..
Do what I suggested, and just add 4 to the value from rand, with rand_max
set to 251. Doing what you show with the values below 4 being rejected, could
potentially result in a slight bias in the numbers. |
|
|
JerryR
Joined: 07 Feb 2008 Posts: 167
|
|
Posted: Thu Oct 15, 2020 10:32 am |
|
|
Yes, good point. I'll use a timer value maybe. |
|
|
|