How to generate a random float values in cooja (c code) if I don't have time.h library to perform srand

152 views Asked by At
float random_value(int min, int max)
{
        float temp = rand() / (float) RAND_MAX;
        return min + temp *(max - min);
}

I have this function, but it is not working in cooja, as it always output the same numbers over and over again, and I don't have the time.h library to make srand(). So, how should I print different random float values in cooja? I should write a c function float random_value (float min, float max) that could be used to implement virtual temperature sensor that could be configured to generate values between min and max value.

2

There are 2 answers

0
Andy J On

If you don't have access to time.h to seed the pseudo-random number generator, another way to use the current pid of the currently-running process.

In fact, unique filenames are sometimes generated this way:

getpid() returns the process ID (PID) of the calling process.
(This is often used by routines that generate unique temporary
filenames.)

Here's a small example that prints the current pid and uses it as an argument to srand():

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main() {
   int pid;
   pid = getpid();
   printf("Current process pid = %d\n", pid);
   srand((unsigned int)pid);
   printf("Random number: %d\n", rand()%100);
   return 0;
}

Running it once:

Current process pid = 197
Random number: 8

Running it again:

Current process pid = 5612
Random number: 76 
0
Basile Starynkevitch On

If you run on Linux, read random(7). you could seed your PRNG by using the getrandom(2) system call or by opening the /dev/random device (see random(4))