CRandom/pcg_demo.mq5
2025-09-19 20:14:50 +00:00

74 lines
6 KiB
MQL5

//+------------------------------------------------------------------+
//| pcg_demo.mq5 |
//| Copyright © 2018, Amr Ali |
//| https://www.mql5.com/en/users/amrali |
//+------------------------------------------------------------------+
#include <Random.mqh>
//--- the random number generator object
CRandom pcg;
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void OnStart()
{
//--- test RandomInteger() function
int arrInt[20];
Print("Random integers in the range [5,100): ");
for(int i=0; i<ArraySize(arrInt); i++)
arrInt[i]=pcg.RandomInteger(5,100);
ArrayPrint(arrInt);
//--- test RandomDouble() function
double arrDbl[10];
Print("Random prices in the range [0.7,2): ");
for(int i=0; i<ArraySize(arrDbl); i++)
arrDbl[i]=pcg.RandomDouble(0.7,2);
ArrayPrint(arrDbl,_Digits);
//--- Generate and print some random dates
Print("Random dates from 1990.01.01 till today: ");
for(int i=0; i<7; i++)
{
double rnd=pcg.RandomDouble(D'1990.01.01',TimeCurrent());
Print((datetime)rnd);
}
//--- Print a random password whose length is 16
string str_pass="";
string alphabet="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for(int i=0; i<16; i++)
{
int rand_pos=pcg.RandomInteger(StringLen(alphabet));
str_pass+=StringSubstr(alphabet,rand_pos,1);
}
Print("Random password: ",str_pass);
//--- 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[pcg.RandomInteger(bound)]++;
PrintFormat("Histogram of pcg.RandomInteger(%d): ",bound);
ArrayPrint(hist,0,", ");
}
//+------------------------------------------------------------------+
/* sample output:
pcg_demo (GBPUSD,H1) Random integers in the range [5,100):
pcg_demo (GBPUSD,H1) 29 99 47 27 16 27 41 94 48 27 18 12 72 12 60 42 60 86 15 62
pcg_demo (GBPUSD,H1) Random prices in the range [0.7,2):
pcg_demo (GBPUSD,H1) 0.70739 1.95768 1.67025 1.66683 0.93186 1.98755 1.11137 1.22964 0.96231 0.74945
pcg_demo (GBPUSD,H1) Random dates from 1990.01.01 till today:
pcg_demo (GBPUSD,H1) 1992.06.01 12:16:10
pcg_demo (GBPUSD,H1) 2006.09.01 05:54:34
pcg_demo (GBPUSD,H1) 1994.03.13 16:52:03
pcg_demo (GBPUSD,H1) 2008.09.23 13:48:29
pcg_demo (GBPUSD,H1) 2012.06.18 07:21:14
pcg_demo (GBPUSD,H1) 2018.05.21 19:19:32
pcg_demo (GBPUSD,H1) 1991.12.10 05:56:25
pcg_demo (GBPUSD,H1) Random password: iCITFfDH1ni6mgDw
pcg_demo (GBPUSD,H1) Histogram of pcg.RandomInteger(13):
pcg_demo (GBPUSD,H1) 7687, 7635, 7684, 7823, 7532, 7662, 7733, 7592, 7787, 7774, 7665, 7737, 7689
*/