66 lines
5.9 KiB
MQL5
66 lines
5.9 KiB
MQL5
//+------------------------------------------------------------------+
|
|
//| MathRand_no_bias.mq5 |
|
|
//| Copyright © 2018, Amr Ali |
|
|
//| https://www.mql5.com/en/users/amrali |
|
|
//+------------------------------------------------------------------+
|
|
#property description "Random number generation using MQL's MathRand() function."
|
|
//+------------------------------------------------------------------+
|
|
//| 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));
|
|
}
|
|
//+------------------------------------------------------------------+
|
|
//| Random integer in the range [min, max) |
|
|
//| Generates random numbers with a uniform distribution (bias-free).|
|
|
//| http://www.pcg-random.org/posts/bounded-rands.html |
|
|
//+------------------------------------------------------------------+
|
|
int MathRandInt(const int min, const int max)
|
|
{
|
|
int range = max - min;
|
|
int limit = (32768 - range) % range;
|
|
int r; do{ r = MathRand(); }while (r < limit);
|
|
return r % range + min;
|
|
}
|
|
//+------------------------------------------------------------------+
|
|
//| |
|
|
//+------------------------------------------------------------------+
|
|
void OnStart()
|
|
{
|
|
//--- Initialize the generator of random numbers
|
|
MathSrand(GetTickCount()^(uint)ChartID());
|
|
|
|
//--- Generate and print some random dates
|
|
Print("Random dates from 1990.01.01 till today: ");
|
|
for(int i=0; i<7; i++)
|
|
{
|
|
double rnd=MathRandDbl(D'1990.01.01',TimeCurrent());
|
|
Print((datetime)rnd);
|
|
}
|
|
//--- check disribution histogram (frequency table)
|
|
int hist[];
|
|
int bound=13;
|
|
int sample=100000;
|
|
ArrayResize(hist,bound);
|
|
ZeroMemory(hist);
|
|
for(int i=0; i<sample; i++)
|
|
hist[MathRandInt(0,bound)]++;
|
|
PrintFormat("Histogram of MathRandInt(0,%d): ",bound);
|
|
ArrayPrint(hist,0,", ");
|
|
}
|
|
//+------------------------------------------------------------------+
|
|
/* sample output:
|
|
MathRand_no_bias (GBPUSD,H1) Random dates from 1990.01.01 till today:
|
|
MathRand_no_bias (GBPUSD,H1) 2013.03.27 04:17:24
|
|
MathRand_no_bias (GBPUSD,H1) 1996.05.02 02:36:29
|
|
MathRand_no_bias (GBPUSD,H1) 2012.11.26 21:52:28
|
|
MathRand_no_bias (GBPUSD,H1) 2017.09.15 17:28:39
|
|
MathRand_no_bias (GBPUSD,H1) 1997.12.28 00:43:49
|
|
MathRand_no_bias (GBPUSD,H1) 1993.02.09 04:56:44
|
|
MathRand_no_bias (GBPUSD,H1) 2015.10.11 02:16:33
|
|
MathRand_no_bias (GBPUSD,H1) Histogram of MathRandInt(0,13):
|
|
MathRand_no_bias (GBPUSD,H1) 7637, 7717, 7655, 7749, 7766, 7595, 7685, 7796, 7648, 7563, 7804, 7672, 7713
|
|
*/
|