# Problem with rand() on FreeBSD



## mad0 (Jan 15, 2013)

Hi
I have simple c++ code:


```
#include <iostream>
#include <ctime>
#include <cstdlib>
int main() {
srand(time(0));
int a=0;
int s=0;
do {
    s=(rand()%7+4);
    std::cout<<s<<",";
    a++;
} while (a!=10);
return 0;
}
```
 g++ -o code code.c on Linux, FreeBSD and OpenBSD.

Results on Linux, run 10 times:
8,5,6,8,8,8,8,4,5,4
8,10,4,6,9,10,5,8,5,10
10,4,4,8,9,9,7,8,10,8
7,9,8,7,4,7,9,6,8,4
8,7,6,6,7,7,4,4,10,9
10,8,5,6,9,10,10,8,10,10
6,7,10,9,9,5,8,9,4,7
6,6,5,4,6,10,4,4,9,4
10,9,5,7,10,8,4,9,7,10
5,9,7,5,8,7,7,6,5,6

And FreeBSD:
7,8,7,8,10,4,6,8,4,5
7,8,9,5,7,9,9,9,5,5
7,7,5,9,4,6,6,9,6,5
7,7,6,8,9,5,8,10,6,5
7,7,8,5,6,10,5,10,7,6
7,7,4,9,10,7,9,4,7,6
7,6,6,6,7,5,6,5,8,6
7,6,9,10,4,9,10,5,8,6
7,6,4,7,8,7,7,6,9,6
7,6,7,4,5,4,4,6,10,6

Why on FreeBSD first number is always the same and second number is changing after +-10sec...?
On OpenBSD, everythik is ok, same as on Linux


----------



## expl (Jan 15, 2013)

From rand(3) man page:
"These interfaces are obsoleted by random(3).". Therefore you should not use it in fresh code.


----------



## mad0 (Jan 15, 2013)

Thanks for answering, it was very helpful.


```
#include <iostream>
#include <ctime>
#include <cstdlib>
int main() {
//srand(time(0));
int a=0;
int s=0;
do {
        s=(arc4random()%7+4);
        std::cout<<s<<",";
        a++;
} while (a!=10);
return 0;
}
```

Work much better.


----------



## Eason (Apr 6, 2013)

I have the same problem recently.

What I found so far is that it only happens when using rand() % 7, which would only give 5 on both my Mac and FreeBSD. When using rand() % OTHER_NUMBER, it doesn't happen. Why would it be the case?


----------



## nslay (Apr 6, 2013)

I know that Linux rand() uses random() underneath. So that would explain the expected behavior.

If FreeBSD uses the traditional rand(), then the lower order bits (such as the last 3 bits or mod 8) will not be very random.


----------



## RichardM (Apr 6, 2013)

Your problem is that you are using the % operator, whereas you want something like rand() / (RAND_MAX+1.0) to generate pseudo-random numbers between 0 and 1. With "%" you will use the lower order bits, which have poor "randomness" properties compared to using the "/" operator, which will use the higher order bits. I don't know much about arc4random(), but if it's a linear congruential generator like rand(), you may still have the same problems with your changed code. There's nothing wrong with rand() as such, if it's used correctly and appropriately (eg, not cryptographic work, and not simulation work as the period may be too short).


----------

