Shop OBEX P1 Docs P2 Docs Learn Events
C: First value from rand() is zero (or other problem?) — Parallax Forums

C: First value from rand() is zero (or other problem?)

John KauffmanJohn Kauffman Posts: 653
edited 2014-12-18 11:25 in Propeller 1
I've written below as an experiment. I always get zero as first output from rand(). Or maybe problem is elsewhere. Any suggestions? Thanks.

#include "simpletools.h"
int main(void){
int randomCurrent;
print("Count\tValues\tModuli range 0-5\n");
for(int count=1;count<=100;count++)
{
randomCurrent = rand();
print("%d.\t%d\t%d\n",count,randomCurrent,randomCurrent%6);
}


Terminal output always shows 0 for first entry:
Count Values Moduli range 0-5
1. 0 0
2. 21468 0
3. 9988 4
4. 22117 1
5. 3498 0

Comments

  • ersmithersmith Posts: 6,053
    edited 2014-12-18 06:31
    The "random" sequence you get from rand() is always the same, and as it happens the default sequence does start with a 0. You can request a different sequence by calling srand(x) with some integer x before the first call to rand(). For example, if you call srand(99) then the first rand() result will return 28592.

    If you have a real time clock or similar input that will vary each time the program runs, you can use a value from this as the input to srand() to ensure that rand() produces a different sequence each time.
  • kuronekokuroneko Posts: 3,623
    edited 2014-12-18 06:33
    srand(CNT) should do the trick.
  • John KauffmanJohn Kauffman Posts: 653
    edited 2014-12-18 06:35
    Perfect, thanks. I was suspicious of the seed.
    I don't have RTC. Do you know of a way to get a seed from Prop ticks?
    Much thanks.
  • John KauffmanJohn Kauffman Posts: 653
    edited 2014-12-18 08:13
    Perfect, much thanks.
  • Heater.Heater. Posts: 21,230
    edited 2014-12-18 11:25
    The Propeller can generate real random numbers by itself without any messing with keyboard click times and so on. See the Real Random object in OBEX:
    http://obex.parallax.com/object/498
    Should be relatively straightforward to implement that in C.

    Depends on how random you want.
Sign In or Register to comment.