-2

I am trying to implement fuction to generate random binary numbers, using the following :

srand(time(NULL)); 
int S = rand() % 2;//continuous random variable between 0 and 1

and then :

 rand()%2; 

is continuously called 2^20 times ... however im not getting proper random numbers.. any suggestions for improvement ?

Is there a data type for binary numbers or eqv.? (instead of declaring an integer)

Also, the only implementation of the seed of srand that i've seen is time(NULL) OR time(0) , is there a way to manipulate the seed to get better random numbers ?

rossum
  • 15,344
  • 1
  • 24
  • 38
TB64
  • 5
  • 1
  • 6
  • 1
    You may want to add the tag "c++" or "c" to your question, since I assume that's what your code is in. – Light Drake Dec 04 '16 at 15:06
  • What do you consider a "proper random number"? What kind of results are you getting? – JJJ Dec 04 '16 at 15:29
  • 1
    Using `rand()%2;` picks off just the low bit of the random number you have just generated. Some PRNGs produce patterns in their low bits, which might be what is causing your problem. Better to avoid the issue by using something like `if (rand() % 10000 >= 5000) ...` which uses more bits of the PRNG output. – rossum Dec 04 '16 at 17:03
  • Are you doing the `srand()` call each time? If so, that's a big no-no. – pjs Dec 04 '16 at 18:29
  • 1
    You asked "...is there a way to manipulate the seed to get better random numbers?" All purely algorithmic PRNGs cycle, i.e., they eventually return to a state they've been in before and from that point on produce the identical sequence of values. All the seed value does is pick the entry point into the cycle. So no, manipulating the seed will give you a different subsequence of the cycle, but has nothing to do with the quality of the random numbers. – pjs Dec 04 '16 at 18:43

1 Answers1

-2

Binary numbers are just numbers in a different base. There is no issue if you just generate integers (base 10) and then, when outputting, convert them to binary.

Check this question for more info on converting an integer into a "binary" string: C++ - Decimal to binary converting

Light Drake
  • 121
  • 3
  • 9
  • 1
    This is not correct, because there is dependence on the PRNG being used. Many PRNGs behave sufficiently well at the integer level, but have very poor performance on individual bits. Many implementations (there's no definitive one last I heard) of `rand()`, in particular, are know to have bad performance in the low bits. – pjs Dec 04 '16 at 18:28
  • 1
    Didn't know that, thought numbers were always the same. See what you mean now though! – Light Drake Dec 06 '16 at 14:05