generating random numbers within a range

• 09-14-2001
tucky
generating random numbers within a range
Hello Everyone

I'm hoping smeone can help me here - I can't see the wood for the trees. I have a requirement to generate random numbers of all types, optionally between a range. I'm OK with integer and smaller numbers, in fact the code I wrote is extremely similar to the stuff on the FAQ. Where I come unstuck is generating doubles, floats and long longs between ranges as % seems to do some truncation. I have tried something like this...

r=(drand48()*(end-start+1))+start;

when end and start can be the end and start of the range, or DBL_MIN and DBL_MAX.

When I do this I don't seem to get a good spread of values, or maybe I'm just misinterpreting the output.

Can anyone enlighten me?

tucky
• 09-14-2001
Prelude
I wonder what your teacher will think if you hand in this :D
Code:

```#include <stdio.h> #include <stdlib.h> #include <time.h>  double rand_mid(int low, int high) {   return (double)(low+rand()%(high-low+1)); } int main(void) {   double x;   int i;   srand(time(NULL));   for(i=0; i<10; i++){     x = rand_mid(1, 100);     printf("A random number from 0 to 99.9: %f\n", x);   } return 0; }```
It's a normal integer rand() generator, except the output is a double ;p I actually haven't had a need to create random doubles or floats, I'll have to give this some thought.

-Prelude
• 09-14-2001
lmov
Code:

```#include <stdlib.h> inline double drand(double low, double high) {     return ((double)rand() * (high - low)) / (double)RAND_MAX + low; }```
Of course, this limits you to a maximum of RAND_MAX numbers between low and high.
• 09-14-2001
tucky
Teacher? This is for a utility at work.

I'll give the code a try - thanks for the help