Do you have an idea to simulate a coin flip?
Numerical recipes in C say they don't trust built-in random number generators when it matters. You could probably implement the algorithm shown in the book as a function ran1 (), which it claims passes all known statistical randomness tests (in 1992) for less than about 10 8 calls.
The basic idea of the ran1 () algorithm is to add an arbitrary move to the output of the random number generator to reduce the sequential low order correlations. They use Shays from Bays-Durham from section 3.2-3.3 in Art of Computer Programming Volume 2, but I would suggest that you can use Fisher-Yates shuffle too.
If you need more random values, then the same document also provides a generator (run2), which should be useful for values at least 10 17 (my guess is based on a period of 2.3 x 10 18 ). There is also a function (ran3) that uses a different method to generate random numbers in case linear congruential generators give you some kind of problem.
You can use any of these functions with your <0.5 to make sure you get an even distribution.
a source to share
What you have is how I will do it. If 0.0 <= Math.random () <1.0, as standard, then (Math.random () <0.5) is going to give you heads when Math.random () is between 0.0 and 0.4999 ... and tails when it's between 0.5 and 0.999 ... This is as honest a coin flip as you can get.
Of course, I assume a good implementation of Math.random ().
a source to share
I cannot comment on people's posts because I have no reputation, but only FYI about the whole <= vs. <topic covered in the Bill. Lizard's comment: Since it can be assumed that random generates any number between 0-1 (which is technically not the case due to the size limitation of the floating point number, but more or less true in practice) there will be no difference in num <= .5 or num <.5 because the probability of getting any one number in any continuous range is 0. IE: P (X = .5) = 0 when X = a random variable between 0 and 1.
a source to share
The only real answer to this question is that you cannot "guarantee" the likelihood. If you think about it, a real coin acceptor does not guarantee a 50/50 probability, it depends on the coin, the person flipping it, and if the coin is dropped and rolled across the floor.;)
The point is that it is "quite random". If you are simulating a coin flip, then the code you posted is more than good.
a source to share