I am trying to generate a random probability with maximum of given probability. How could we generate a random real value between 0 and 0.5 in C?
-
1I would suggest to write code the generates a value between 0 and 1, then refine it to limit to 0.5. – Al Lelopath Nov 04 '14 at 18:23
-
1Here is a nice video about this issue : http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful – francis Nov 04 '14 at 18:23
-
With just C? You can't. The best thing you could do is read a truly random value from a entropy source that gets fed with entropy from the physical world. – datenwolf Nov 04 '14 at 18:24
-
possible duplicate of [How to generate a random number in C?](http://stackoverflow.com/questions/822323/how-to-generate-a-random-number-in-c) – Craig S. Anderson Nov 04 '14 at 18:25
-
2There are infinitely-many real numbers from 0 to 0.5, each with a probability of 0% of being chosen by your hypothetical random number generator. To try to salvage this question, I will ask you: to how many decimal places do you want to generate these random numbers? – wjmolina Nov 04 '14 at 18:25
1 Answers
You cannot generate a really random number in portable C99. But you could use some PRNG (and perhaps seed it with the current time).
And computers don't know about true real numbers. Only floating point. See http://floating-point-gui.de/
Actually I believe that the universe does not know about real numbers (think about some cardinality argument similar to Cantor's diagonal argument). But ask physicists or philosophers.
Some operating systems or implementations have PRNGs, and some systems (including) hardware have even genuine random generators.
Read about random(3) & drand48(3) if your system has it. If on Linux, read also random(4)
You might try
double my_random_number /* between 0 & 0.5 */ = drand48() * 0.5;
to generate an almost uniformly distributed random number >= 0 and < 0.5
See also C++11 standard header <random>
if you accept to code in C++ ...

- 223,805
- 18
- 296
- 547
-
1Actually, `/dev/random` on Unix-like boxes and `CryptGenRandom` on Windows boxes may very well get entropy from hardware-based random number generators available on many modern computers, and so may be truly random, not just algorithmically pseudo-random. – Lee Daniel Crocker Nov 04 '14 at 18:34
-
Didn't I mention that in my second paragraph. And `random(4)` tells about it. – Basile Starynkevitch Nov 04 '14 at 18:36
-
3I think he's using "real" in the mathematical sense; http://en.wikipedia.org/wiki/Real_number rather than "real" in the "truly" sense: http://en.wikipedia.org/wiki/Random_number_generation#.22True.22_random_numbers_vs._pseudo-random_numbers Good answer though. – DavidO Nov 04 '14 at 18:36
-
A pseudo-random number uniformly distributed between 0 and 1 with time as seed, and multiplied by max value (0.5) solved. Yes, I used "real" in mathematical sense. – Syam Nov 04 '14 at 18:59