How can I make a random number - page 2

 
amando:

Could you explain how your reply relates to the original post?

 
Denis Kirichenko:
MQL5 has its own.

Than kyou for pointing this out. In fact i did not come across these functions.

 
//+------------------------------------------------------------------+
//| Random double in the range [min, max)                            |
//| Generates doubles rounded down to the nearest multiple of 1/2^15 |
//+------------------------------------------------------------------+
double MathRandDbl(const double min, const double max)
  {
   double f   = (MathRand() / 32768.0);
   return min + (f * (max - min));
  }


Or simply for the case [0, 1)

double rnd01 = MathRand()/32768.0;


For a more reliable usage, use CRandom library.

https://www.mql5.com/en/code/25843

Class CRandom
Class CRandom
  • www.mql5.com
Random number generation using the 32-bit PCG generator.
 
Amir Yacoby:

Or just use (for 0 to 1 doubles)

double d=MathMod(MathRand(),100)/100;


Hi, Amir. I would like to point to a subtle issue in your answer, that is the modulo bias.


Because, modulo by 100 does not divide the RAND_MAX range evenly, as the range of mql random number generator is from 0 to 32767 (i.e., RAND_MAX = 2^15 - 1).


So it will lead to modulo bias. As a result, the generated random numbers in the range 0 to 0.67 will have a higher chance to appear than those in the range 0.68 to 1.0


For more thorough explanation of modulo bias please see http://www.pcg-random.org/posts/bounded-rands.html


Thank you.

Efficiently Generating a Number in a Range
  • 2018.07.22
  • M.E. O'Neill
  • www.pcg-random.org
The vast majority of my posts about random number generation have focused on looking at the properties of different generation schemes. But, perhaps surprisingly, the performance of your randomized algorithm may hinge not on the generation scheme you chose, but on other factors. In this post (inspired by and building on an excellent recent...
 
amrali:


Hi, Amir. I would like to point to a subtle issue in your answer, that is the modulo bias.


Because, modulo by 100 does not divide the RAND_MAX range evenly, as the range of mql random number generator is from 0 to 32767 (i.e., RAND_MAX = 2^15 - 1).


So it will lead to modulo bias. As a result, the generated random numbers in the range 0 to 0.67 will have a higher chance to appear than those in the range 0.68 to 1.0


For more thorough explanation of modulo bias please see http://www.pcg-random.org/posts/bounded-rands.html


Thank you.

That's correct. If OP needs an unbiased random, better use one of the unbiased options to calculate it.

Reason: