I wrote this function to get a pseudo random float between 0 .. 1 inclusive:
float randomFloat()
{
float r = (float)rand()/(float)RAND_MAX;
retur
That is because the C random-generator is a pseudo-random generator (and that is, BTW, a very good thing, with many applications). (The ANSI C standard requires such a pseudo-random generator)
Essentially each time your console application is re-started it uses the same [default] seed for the random generator.
by adding a line like
srand(time(NULL));
you will get a distinct seed each time, and the sequence of number produced with vary accordingly.
Note: you only need to call srand() once, not before each time you call rand().
Edit: (Test/Debug-time hint)
[from a remark by Artelius]
For testing purposes, it's best to srand(SOME_CONST), and change the value of the constant between runs. This way if a bug manifests itself due to some combination of random numbers, you'll be able to reproduce it.
Do you call it more than once? rand() will always return the same pseudo random. You might want to call srand() with some nice seed, like the current time.
You need to call
srand(time(NULL));
before using rand
for the first time. time
is in <time.h>
.
EDIT: As Jonathan Leffler points out, this is easily predicted, so don't try using it for cryprography.
drand48 is perfect for your usage, better than (float)rand()/RAND_MAX
, because
The
drand48()
anderand48()
functions return non-negative, double-precision, floating-point values, uniformly distributed over the interval [0.0 , 1.0].
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int i;
srand48(time(NULL));
for (i = 0; i < 10; i++)
printf("%g\n", drand48());
return 0;
}
You have to initialize a random seed with
void srand ( unsigned int seed );
You can take for example the system time.