-1

How can i create function in C , which would generate random number }(type double) between set arguments? In lot of languagues its simply just

function randomnumber(min, max) {
  return Math.random() * (max - min + 1) + min;
}

but i fail to find any good solution for type double in c.

Darlyn
  • 4,715
  • 12
  • 40
  • 90

2 Answers2

1

There are several methods. Answer 1 above is ok for min, max as doubles. The important thing to remember for rand() is that it returns a random integer between 0 and RAND_MAX inclusive. RAND_MAX is a least 2^15, but on most systems 2^31. If min and max are integers and their difference is less than RAND_MAX then a very easy method is:

delta = max - min;
r  = rand() % delta + min;
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
akm27
  • 56
  • 3
0
#include <stdlib.h> /* rand(), srand(), RAND_MAX */

double randd(double min, double max) {
    int r = rand();
    double delta = max - min; /* assume max > min */
    double tmp = r / (RAND_MAX + 1.0); /* generate up to but excluding max */
    return tmp * delta + min;
}
pmg
  • 106,608
  • 13
  • 126
  • 198
  • See it running: http://ideone.com/EOGwIJ – pmg Nov 06 '15 at 17:04
  • 1
    OP was not very specific on the goals, yet this answer will likely not generate every `double` between `min` and `max`. – chux - Reinstate Monica Nov 06 '15 at 17:06
  • @chux Depending on `min` and `max` this answer, with its bias, can generate every `double` between those values .... and repeat some of the answers to boot (think 52 bits for the mantissa and 63 bits for the PRNG). – pmg Nov 07 '15 at 15:41
  • Rare machines have a `int` of 63+ bits - the return type of `rand()` - more likely to be 32-bit (or even 16) and so insufficient to generate all the range of `double` with many `min`, `max`. Had this answers referenced a 63 bit PRNG or express how to compensate for insufficient `RAND_MAX` range, I would have not commented so. – chux - Reinstate Monica Nov 08 '15 at 05:18