-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.

5
  • ... you're using floor so you really want a random integer? Commented Nov 6, 2015 at 16:37
  • indeed , i just noticed , thanks for pointing out Commented Nov 6, 2015 at 16:39
  • function...? :) return type? type of arguments? Commented Nov 6, 2015 at 16:48
  • 1
    @ameyCU Proposed duplicate deals with float, yet the post request double. That extra precision/range poses additional concerns that a good answer would provide. Commented Nov 6, 2015 at 16:59
  • trolkura what type of distribution do you want: linear between max and min? It is easier to not include one of the limits so like [min...max) rather than [min... max]. Do you want to be able to generate every double between min and max or just most of them sufficient? Commented Nov 6, 2015 at 17:04

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

Comments

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;
}

4 Comments

See it running: ideone.com/EOGwIJ
OP was not very specific on the goals, yet this answer will likely not generate every double between min and max.
@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).
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.