TestRandom.cpp 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // Copyright (c) Electronic Arts Inc. All rights reserved.
  3. ///////////////////////////////////////////////////////////////////////////////
  4. #ifdef _MSC_VER
  5. #pragma warning(disable: 4244) // This warning is being generated due to a bug in VC++.
  6. #endif
  7. #include <EABase/eabase.h>
  8. #include <EAStdC/EARandom.h>
  9. #include <EAStdC/EARandomDistribution.h>
  10. #include <EAStdCTest/EAStdCTest.h>
  11. #include <EATest/EATest.h>
  12. #include <EASTL/bitset.h>
  13. #ifdef _MSC_VER
  14. #pragma warning(push, 0)
  15. #pragma warning(disable: 4275) // non dll-interface class 'stdext::exception' used as base for dll-interface class 'std::bad_cast'
  16. #endif
  17. #ifndef EA_PLATFORM_ANDROID
  18. #include <algorithm>
  19. #endif
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <math.h>
  23. #if defined(_MSC_VER) && defined(EA_PLATFORM_MICROSOFT)
  24. #include <crtdbg.h>
  25. #endif
  26. #if defined(EA_PLATFORM_WINDOWS)
  27. #include <Windows.h>
  28. #endif
  29. #if EASTDC_TIME_H_AVAILABLE
  30. #include <time.h>
  31. #endif
  32. #ifdef _MSC_VER
  33. #pragma warning(pop)
  34. #pragma warning(push)
  35. #pragma warning(disable: 4365) // 'argument' : conversion from 'int' to 'uint32_t', signed/unsigned mismatch
  36. #endif
  37. using namespace EA::StdC;
  38. // Forward declarations
  39. void rt_init(int binmode);
  40. void rt_add(void* buf, int bufl);
  41. void rt_end(double* r_ent, double* r_chisq, double* r_mean, double* r_montepicalc, double* r_scc);
  42. static int TestDieHard()
  43. {
  44. int nErrorCount(0);
  45. // Write out 9MB file for DieHard tests.
  46. #if defined(EA_PLATFORM_WINDOWS) && EA_WINAPI_FAMILY_PARTITION(EA_WINAPI_PARTITION_DESKTOP)
  47. if(GetAsyncKeyState(VK_SCROLL)) // If the Scroll Lock key is alive.
  48. {
  49. // Ideally we would port the DieHard code to here, but it is not well
  50. // written for modularity. For the time being, we write out the 9MB
  51. // data file that DieHard.exe can analyze. As of this writing, DieHard.exe
  52. // is part of the EAOS UTF Research repository.
  53. {
  54. RandomLinearCongruential randomLC;
  55. FILE* pFile = fopen("RandomLinearCongruentialData.txt", "w");
  56. if(pFile)
  57. {
  58. for(uint32_t i = 0; i < 12000000; i += 4)
  59. {
  60. const uint32_t value = randomLC.RandomUint32Uniform();
  61. fwrite(&value, 1, 4, pFile);
  62. }
  63. fclose(pFile);
  64. }
  65. }
  66. {
  67. RandomMersenneTwister randomMT;
  68. FILE* pFile = fopen("RandomMersenneTwisterData.txt", "w");
  69. if(pFile)
  70. {
  71. for(uint32_t i = 0; i < 12000000; i += 4)
  72. {
  73. const uint32_t value = randomMT.RandomUint32Uniform();
  74. fwrite(&value, 1, 4, pFile);
  75. }
  76. fclose(pFile);
  77. }
  78. }
  79. }
  80. #endif
  81. return nErrorCount;
  82. }
  83. namespace
  84. {
  85. #if defined(EA_PLATFORM_DESKTOP) && !defined(EA_DEBUG)
  86. // This exists for the purpose of testing distributions. It implements a seed that is continuously
  87. // increasting and thus over the course of 0x100000000 (2^32) calls to RandomUint32Uniform returns a statistically
  88. // even distribution of bits. Note that truly random data won't behave this way and formal tests for
  89. // randomness would identify this as being not random. But that's not the purpose of this class;
  90. // the purpose is to help test if there are distribution problems in the range and distribution adapters.
  91. // Note that it's important that you do 0x100000000 calls with this or else the results of it won't
  92. // be evenly distributed as designed.
  93. class FakeIncrementingRandom
  94. {
  95. public:
  96. FakeIncrementingRandom()
  97. : mnSeed(0) {}
  98. //FakeIncrementingRandom(const FakeIncrementingRandom& x)
  99. // : mnSeed(x.mnSeed) {}
  100. //FakeIncrementingRandom& operator=(const FakeIncrementingRandom& x)
  101. // { mnSeed = x.mnSeed; return *this; }
  102. //uint32_t GetSeed() const
  103. // { return mnSeed; }
  104. //void SetSeed(uint32_t nSeed)
  105. // { mnSeed = nSeed; }
  106. //uint32_t operator()(uint32_t nLimit)
  107. // { return EA::StdC::RandomLimit(*this, nLimit); }
  108. uint32_t RandomUint32Uniform()
  109. { return mnSeed++; }
  110. protected:
  111. uint32_t mnSeed;
  112. };
  113. #endif
  114. }
  115. // TestRandom
  116. // Note that thus function itself is not meant as a comprehensive
  117. // test for randomness. Instead this function does a basic test
  118. // for randomness and then optionally writes out files to disk
  119. // for analysis by a comprehensive tool like DieHard.
  120. //
  121. int TestRandom()
  122. {
  123. int nErrorCount(0);
  124. EA::UnitTest::Report("TestRandom\n");
  125. { // Bug report regression.
  126. // User Fei Jiang reports that RandomLinearCongruential::RandomUnit32Uniform(uint32_t nLimit) returns
  127. // different values on PS3 in debug vs. debug-opt builds with SN compiler.
  128. RandomLinearCongruential rlc(UINT32_C(2474210934));
  129. uint32_t seed = rlc.GetSeed();
  130. //EA::UnitTest::Report("seed: %u\n", (unsigned)seed);
  131. EATEST_VERIFY(seed == UINT32_C(2474210934));
  132. uint32_t result = rlc.RandomUint32Uniform(57);
  133. //EA::UnitTest::Report("result: %u\n", (unsigned)result);
  134. EATEST_VERIFY(result == 23); // 743483
  135. }
  136. // Load priming
  137. // We call a function from each generator used below to minimize
  138. // an loading effects on benchmarking.
  139. int rTemp = rand();
  140. EATEST_VERIFY(rTemp >= 0); // "Returns a pseudo-random integral number in the range 0 to RAND_MAX."
  141. RandomLinearCongruential randomLCPrimer;
  142. randomLCPrimer.RandomUint32Uniform();
  143. RandomMersenneTwister randomMTPrimer;
  144. randomMTPrimer.RandomUint32Uniform();
  145. TestDieHard();
  146. //#define SPEED_TESTS_ENABLED
  147. #ifdef SPEED_TESTS_ENABLED
  148. // Speed tests.
  149. // Results on a Pentium 4 PC were:
  150. // rand(): 8172 clocks.
  151. // RandomLinearCongruential: 4687 clocks.
  152. // RandomMersenneTwister: 6157 clocks.
  153. {
  154. clock_t timeStart;
  155. clock_t timeTotal;
  156. const int kIterationCount(5000000);
  157. timeStart = clock();
  158. for(int i(0); i < kIterationCount; i++)
  159. EA::UnitTest::WriteToEnsureFunctionCalled() = (int)rand();
  160. timeTotal = clock() - timeStart;
  161. EA::UnitTest::Report("rand(): %d clocks.\n", (int)timeTotal);
  162. timeStart = clock();
  163. for(int i(0); i < kIterationCount; i++)
  164. EA::UnitTest::WriteToEnsureFunctionCalled() = (int)(rand() % 37997);
  165. timeTotal = clock() - timeStart;
  166. EA::UnitTest::Report("rand() w/limit: %d clocks.\n", (int)timeTotal);
  167. RandomLinearCongruential randomLC;
  168. timeStart = clock();
  169. for(int i(0); i < kIterationCount; i++)
  170. EA::UnitTest::WriteToEnsureFunctionCalled() = (int)randomLC.RandomUint32Uniform();
  171. timeTotal = clock() - timeStart;
  172. EA::UnitTest::Report("RandomLinearCongruential: %d clocks.\n", (int)timeTotal);
  173. timeStart = clock();
  174. for(int i(0); i < kIterationCount; i++)
  175. EA::UnitTest::WriteToEnsureFunctionCalled() = (int)randomLC.RandomUint32Uniform(37997);
  176. timeTotal = clock() - timeStart;
  177. EA::UnitTest::Report("RandomLinearCongruential w/limit: %d clocks.\n", (int)timeTotal);
  178. RandomMersenneTwister randomMT;
  179. timeStart = clock();
  180. for(int i(0); i < kIterationCount; i++)
  181. EA::UnitTest::WriteToEnsureFunctionCalled() = (int)randomMT.RandomUint32Uniform();
  182. timeTotal = clock() - timeStart;
  183. EA::UnitTest::Report("RandomMersenneTwister: %d clocks.\n", (int)timeTotal);
  184. timeStart = clock();
  185. for(int i(0); i < kIterationCount; i++)
  186. EA::UnitTest::WriteToEnsureFunctionCalled() = (int)randomMT.RandomUint32Uniform(32997);
  187. timeTotal = clock() - timeStart;
  188. EA::UnitTest::Report("RandomMersenneTwister w/limit: %d clocks.\n", (int)timeTotal);
  189. }
  190. #endif
  191. // Test output ranges
  192. { // RandomLinearCongruential test
  193. RandomLinearCongruential random;
  194. int32_t nRandom;
  195. double dRandom;
  196. for(unsigned i(0); i < 100; i++)
  197. {
  198. for(uint32_t j(5); j < (UINT32_MAX / 2); j *= 5)
  199. {
  200. uint32_t nU32 = random.RandomUint32Uniform(j);
  201. EATEST_VERIFY(nU32 < j);
  202. dRandom = random.RandomDoubleUniform((double)j);
  203. EATEST_VERIFY(0.0 <= dRandom && dRandom < j);
  204. dRandom = random.RandomDoubleUniform();
  205. EATEST_VERIFY(0.0 <= dRandom && dRandom < 1.0);
  206. }
  207. nRandom = Random2(random);
  208. EATEST_VERIFY(nRandom < 2);
  209. nRandom = Random4(random);
  210. EATEST_VERIFY(nRandom < 4);
  211. nRandom = Random8(random);
  212. EATEST_VERIFY(nRandom < 8);
  213. nRandom = Random16(random);
  214. EATEST_VERIFY(nRandom < 16);
  215. nRandom = Random32(random);
  216. EATEST_VERIFY(nRandom < 32);
  217. nRandom = Random64(random);
  218. EATEST_VERIFY(nRandom < 642);
  219. nRandom = Random128(random);
  220. EATEST_VERIFY(nRandom < 128);
  221. nRandom = Random256(random);
  222. EATEST_VERIFY(nRandom < 256);
  223. // RandomPowerOfTwo
  224. for(uint32_t k(1); k < 31; k++)
  225. {
  226. nRandom = RandomPowerOfTwo(random, k);
  227. EATEST_VERIFY((uint32_t)nRandom < (uint32_t)(2 << k));
  228. }
  229. // RandomInt32UniformRange
  230. for(int32_t nBegin(-10000); nBegin < 10000; nBegin += Random256(random))
  231. {
  232. int32_t nEnd = nBegin + 1 + Random256(random);
  233. int32_t iRandom = RandomInt32UniformRange(random, nBegin, nEnd);
  234. EATEST_VERIFY_F((iRandom >= nBegin) && (iRandom < nEnd), "RandomInt32UniformRange failure: iRandom: %I32d, nBegin: %I32d, nEnd: %I32d", iRandom, nBegin, nEnd);
  235. }
  236. // RandomDoubleUniformRange
  237. for(int32_t dBegin(-10000); dBegin < 10000; dBegin += Random256(random))
  238. {
  239. int32_t dEnd = dBegin + 1 + Random256(random);
  240. dRandom = RandomDoubleUniformRange(random, (double)dBegin, (double)dEnd);
  241. EATEST_VERIFY_F((dRandom >= dBegin) && (dRandom < dEnd), "RandomDoubleUniformRange failure: dRandom: %f, dBegin: %f, dEnd: %f", dRandom, (double)dBegin, (double)dEnd);
  242. }
  243. // RandomUint32WeightedChoice
  244. const uint32_t kLimit = 37;
  245. float weights[kLimit];
  246. for(uint32_t q(0); q < kLimit; q++)
  247. weights[q] = (float)RandomDoubleUniformRange(random, 0.5, 30.0);
  248. for(uint32_t r(0); r < 1000; r++)
  249. {
  250. uint32_t nU32 = RandomUint32WeightedChoice(random, kLimit, weights);
  251. EATEST_VERIFY_F(nU32 < kLimit, "RandomUint32WeightedChoice failure: nU32: %I32u, kLimit: %I32u", nU32, kLimit);
  252. }
  253. // RandomInt32GaussianRange
  254. for(int r(0); r < 1000; r++)
  255. {
  256. const int32_t nBegin = (int32_t)random.RandomUint32Uniform(1000);
  257. const int32_t nEnd = nBegin + (int32_t)random.RandomUint32Uniform(1000) + 1;
  258. const int32_t iRandom = RandomInt32GaussianRange(random, nBegin, nEnd);
  259. EATEST_VERIFY((iRandom >= nBegin) && (iRandom < nEnd));
  260. }
  261. // RandomFloatGaussianRange
  262. for(int r(0); r < 1000; r++)
  263. {
  264. const float fBegin = (float)random.RandomDoubleUniform(1000);
  265. const float fEnd = fBegin + (float)random.RandomDoubleUniform(1000) + 1.0f;
  266. const float fRandom = RandomFloatGaussianRange(random, fBegin, fEnd);
  267. EATEST_VERIFY((fRandom >= fBegin) && (fRandom < fEnd));
  268. }
  269. // RandomInt32TriangleRange
  270. for(int r(0); r < 1000; r++)
  271. {
  272. const int32_t nBegin = (int32_t)random.RandomUint32Uniform(1000);
  273. const int32_t nEnd = nBegin + (int32_t)random.RandomUint32Uniform(1000) + 1;
  274. const int32_t iRandom = RandomInt32TriangleRange(random, nBegin, nEnd);
  275. EATEST_VERIFY((iRandom >= nBegin) && (iRandom < nEnd));
  276. }
  277. // RandomFloatTriangleRange
  278. for(int r(0); r < 1000; r++)
  279. {
  280. const float fBegin = (float)random.RandomDoubleUniform(1000);
  281. const float fEnd = fBegin + (float)random.RandomDoubleUniform(1000) + 1.0f;
  282. const float fRandom = RandomFloatTriangleRange(random, fBegin, fEnd);
  283. EATEST_VERIFY((fRandom >= fBegin) && (fRandom < fEnd));
  284. }
  285. }
  286. }
  287. { // RandomInt32Poisson
  288. const float fMean = 5.f;
  289. const size_t maxK = 30;
  290. RandomMersenneTwister random;
  291. for(int i = 0; i < 1000; i++)
  292. {
  293. int32_t rn = RandomInt32Poisson(random.RandomDoubleUniform(), fMean);
  294. EATEST_VERIFY(rn < maxK);
  295. }
  296. }
  297. { // RandomLinearCongruential test
  298. RandomMersenneTwister random;
  299. int32_t nRandom;
  300. double dRandom;
  301. for(unsigned i(0); i < 1000; i++)
  302. {
  303. for(uint32_t j(5); j < UINT32_MAX / 2; j *= 5)
  304. {
  305. uint32_t nU32 = random.RandomUint32Uniform(j);
  306. EATEST_VERIFY(nU32 < j);
  307. dRandom = random.RandomDoubleUniform((double)j);
  308. EATEST_VERIFY(0.0 <= dRandom && dRandom < j);
  309. dRandom = random.RandomDoubleUniform();
  310. EATEST_VERIFY(0.0 <= dRandom && dRandom < 1.0);
  311. }
  312. nRandom = Random2(random);
  313. EATEST_VERIFY(nRandom < 2);
  314. nRandom = Random4(random);
  315. EATEST_VERIFY(nRandom < 4);
  316. nRandom = Random8(random);
  317. EATEST_VERIFY(nRandom < 8);
  318. nRandom = Random16(random);
  319. EATEST_VERIFY(nRandom < 16);
  320. nRandom = Random32(random);
  321. EATEST_VERIFY(nRandom < 32);
  322. nRandom = Random64(random);
  323. EATEST_VERIFY(nRandom < 64);
  324. nRandom = Random128(random);
  325. EATEST_VERIFY(nRandom < 128);
  326. nRandom = Random256(random);
  327. EATEST_VERIFY(nRandom < 256);
  328. for(uint32_t k(1); k < 31; k++)
  329. {
  330. nRandom = RandomPowerOfTwo(random, k);
  331. EATEST_VERIFY((uint32_t)nRandom < (uint32_t)(2 << k));
  332. }
  333. for(int nBegin(-10000); nBegin < 10000; nBegin += Random256(random))
  334. {
  335. int32_t nEnd = nBegin + 1 + Random256(random);
  336. int32_t iRandom = RandomInt32UniformRange(random, nBegin, nEnd);
  337. EATEST_VERIFY((iRandom >= nBegin) && (iRandom < nEnd));
  338. }
  339. for(int dBegin(-10000); dBegin < 10000; dBegin += Random256(random))
  340. {
  341. int32_t dEnd = dBegin + 1 + Random256(random);
  342. dRandom = RandomDoubleUniformRange(random, (double)dBegin, (double)dEnd);
  343. EATEST_VERIFY((dRandom >= dBegin) && (dRandom < dEnd));
  344. }
  345. const unsigned int kLimit = 37;
  346. float weights[kLimit];
  347. for(unsigned int q(0); q < kLimit; q++)
  348. weights[q] = (float)RandomDoubleUniformRange(random, 0.5, 30.0);
  349. for(unsigned int r(0); r < 100; r++)
  350. {
  351. uint32_t nU32 = RandomUint32WeightedChoice(random, kLimit, weights);
  352. EATEST_VERIFY(nU32 < kLimit);
  353. }
  354. }
  355. }
  356. //NOTICE:
  357. //Need Paul to look at this.
  358. //At times, getting values outside of the assertion range.
  359. #if !defined(EA_PLATFORM_IPHONE)
  360. // Do basic randomness testing.
  361. // Just because a random number generator passes known basic tests
  362. // doesn't mean it doesn't have a major flaw.
  363. { // C runtime rand() test, provided for comparison.
  364. int nErrorCountCRand(0); //We don't want to report these as part of our test.
  365. rt_init(false);
  366. for(int i(0); i < 100000; i++)
  367. {
  368. uint8_t nRandom = (uint8_t)(rand() & UINT8_MAX);
  369. rt_add(&nRandom, sizeof(nRandom));
  370. }
  371. // See the rt_end documentation for detailed explanations
  372. // of what each of these metrics mean.
  373. double r_ent, r_chisq, r_mean, r_montepicalc, r_scc;
  374. rt_end(&r_ent, &r_chisq, &r_mean, &r_montepicalc, &r_scc);
  375. if(r_ent < 7.8)
  376. nErrorCountCRand++;
  377. else if(r_chisq < 200)
  378. nErrorCountCRand++;
  379. else if(r_mean < 127.2 || r_mean > 127.9)
  380. nErrorCountCRand++;
  381. else if(r_montepicalc < 3.11 || r_montepicalc > 3.17)
  382. nErrorCountCRand++;
  383. else if(r_scc > 0.01)
  384. nErrorCountCRand++;
  385. }
  386. { // RandomLinearCongruential test
  387. RandomLinearCongruential random;
  388. rt_init(false);
  389. for(int i(0); i < 100000; i++)
  390. {
  391. uint32_t nRandom = random.RandomUint32Uniform();
  392. rt_add(&nRandom, sizeof(nRandom));
  393. }
  394. // See the rt_end documentation for detailed explanations
  395. // of what each of these metrics mean.
  396. double r_ent, r_chisq, r_mean, r_montepicalc, r_scc;
  397. rt_end(&r_ent, &r_chisq, &r_mean, &r_montepicalc, &r_scc);
  398. EATEST_VERIFY(r_ent >= 7.8);
  399. //EATEST_VERIFY(r_chisq >= 200); Disabled until we can figure out why it occasionally fails.
  400. //EATEST_VERIFY(r_mean >= 127.2 && r_mean < 127.9); Disabled until we can figure out why it occasionally fails.
  401. EATEST_VERIFY(r_montepicalc >= 3.11 && r_montepicalc < 3.17);
  402. EATEST_VERIFY(r_scc <= 0.01);
  403. }
  404. { // RandomMersenneTwister test
  405. RandomMersenneTwister random;
  406. rt_init(false);
  407. for(int i(0); i < 100000; i++)
  408. {
  409. uint32_t nRandom = random.RandomUint32Uniform();
  410. rt_add(&nRandom, sizeof(nRandom));
  411. }
  412. // See the rt_end documentation for detailed explanations
  413. // of what each of these metrics mean.
  414. double r_ent, r_chisq, r_mean, r_montepicalc, r_scc;
  415. rt_end(&r_ent, &r_chisq, &r_mean, &r_montepicalc, &r_scc);
  416. EATEST_VERIFY(r_ent >= 7.8);
  417. //EATEST_VERIFY(r_chisq >= 200); Disabled until we can figure out why it occasionally fails.
  418. //EATEST_VERIFY(r_mean >= 127.2 && r_mean < 127.9); Disabled until we can figure out why it occasionally fails.
  419. EATEST_VERIFY(r_montepicalc >= 3.11 && r_montepicalc < 3.17);
  420. EATEST_VERIFY(r_scc <= 0.01);
  421. }
  422. #endif
  423. { // RandomMersenneTwister seed serialization test.
  424. RandomMersenneTwister rmt;
  425. uint32_t seedArray[RandomMersenneTwister::kSeedArrayCount * 2];
  426. uint32_t rand1, rand2;
  427. unsigned size;
  428. size = rmt.GetSeed(seedArray, RandomMersenneTwister::kSeedArrayCount);
  429. EATEST_VERIFY(size == RandomMersenneTwister::kSeedArrayCount);
  430. rand1 = rmt.RandomUint32Uniform();
  431. rmt.RandomUint32Uniform();
  432. rmt.SetSeed(seedArray, size);
  433. rand2 = rmt.RandomUint32Uniform();
  434. EATEST_VERIFY(rand1 == rand2);
  435. size = rmt.GetSeed(seedArray, RandomMersenneTwister::kSeedArrayCount * 2);
  436. EATEST_VERIFY(size == RandomMersenneTwister::kSeedArrayCount);
  437. rand1 = rmt.RandomUint32Uniform();
  438. rmt.RandomUint32Uniform();
  439. rmt.SetSeed(seedArray, size);
  440. rand2 = rmt.RandomUint32Uniform();
  441. EATEST_VERIFY(rand1 == rand2);
  442. size = rmt.GetSeed(seedArray, RandomMersenneTwister::kSeedArrayCount / 2);
  443. EATEST_VERIFY(size == RandomMersenneTwister::kSeedArrayCount / 2);
  444. rand1 = rmt.RandomUint32Uniform();
  445. rmt.RandomUint32Uniform();
  446. rmt.SetSeed(seedArray, size);
  447. // We can't test for equality or inequality of rand1 and rand2
  448. // This is just a pathological test.
  449. size = rmt.GetSeed(seedArray, 0);
  450. EATEST_VERIFY(size == 0);
  451. rand1 = rmt.RandomUint32Uniform();
  452. rmt.RandomUint32Uniform();
  453. rmt.SetSeed(seedArray, size);
  454. rand2 = rmt.RandomUint32Uniform();
  455. EATEST_VERIFY(rand1 != rand2); // They should be different (actually one out of 4 billion times they shouldn't be) because we didn't read the entire state, but only half of it.
  456. }
  457. {
  458. #if defined(EA_PLATFORM_DESKTOP) && !defined(EA_DEBUG) // Do this test only on fast machines, as it's compute-intensive.
  459. // Range tests with FakeIncrementingRandom
  460. const size_t sizes[] = { 2, 5, 10 };
  461. eastl::vector<uint32_t> countBuckets(sizes[EAArrayCount(sizes) - 1], 0);
  462. for(size_t a = 0; a < EAArrayCount(sizes); a++)
  463. {
  464. size_t s = sizes[a];
  465. FakeIncrementingRandom fir;
  466. eastl::fill(countBuckets.begin(), countBuckets.end(), 0);
  467. for(uint64_t i = 0, iEnd = UINT64_C(0x100000000) / s * s; i < iEnd; i++)
  468. {
  469. if((i % 0x10000000) == 0)
  470. EA::UnitTest::Report("."); // Keepalive output.
  471. uint32_t b = EA::StdC::RandomLimit(fir, static_cast<uint32_t>(s));
  472. countBuckets[b]++;
  473. }
  474. for(eastl_size_t b = 1, c = countBuckets[0]; b < s; b++)
  475. {
  476. if(countBuckets[b] != c)
  477. {
  478. EATEST_VERIFY(countBuckets[b] == c);
  479. EA::UnitTest::Report("Random distribution result buckets for limit of %I32u:\n ", (uint32_t)s);
  480. for(eastl_size_t bb = 0, bbEnd = s; bb < bbEnd; bb++)
  481. EA::UnitTest::Report("%I32u%s", (uint32_t)countBuckets[bb], ((bb % 16) == 15) ? "\n" : " ");
  482. EA::UnitTest::Report("\n");
  483. break;
  484. }
  485. }
  486. EA::UnitTest::Report(".\n"); // Keep alive output.
  487. }
  488. #endif
  489. }
  490. // Write out files suitable for the DieHard test suite.
  491. // The version of DieHard that this author most recently
  492. // worked with requires 8404992 bytes of data in a file.
  493. // A copy of DieHard.exe should accompany this test.
  494. // Currently, you drag a file onto it to get the results
  495. // of the test. In the future we can implement the entire
  496. // test within this file. It is about 3500 lines of code
  497. // and would require some massaging to make it work
  498. // smoothly with a unit testing system.
  499. return nErrorCount;
  500. }
  501. ///////////////////////////////////////////////////////////////////////////////
  502. // Ent Chi-Squared functions
  503. //
  504. // Home:
  505. // http://www.fourmilab.ch/random/
  506. // License:
  507. // This software is in the public domain. Permission to use, copy, modify,
  508. // and distribute this software and its documentation for any purpose and
  509. // without fee is hereby granted, without any conditions or restrictions.
  510. // This software is provided "as is" without express or implied warranty.
  511. ///////////////////////////////////////////////////////////////////////////////
  512. //
  513. // Entropy
  514. // The information density of the contents of the file, expressed as a
  515. // number of bits per character. The results above, which resulted from
  516. // processing an image file compressed with JPEG, indicate that the
  517. // file is extremely dense in information--essentially random.
  518. // Hence, compression of the file is unlikely to reduce its size.
  519. // By contrast, the C source code of the program has entropy of about
  520. // 4.9 bits per character, indicating that optimal compression of the
  521. // file would reduce its size by 38%. [Hamming, pp. 104-108]
  522. //
  523. // Chi-square Test
  524. // The chi-square test is the most commonly used test for the randomness
  525. // of data, and is extremely sensitive to errors in pseudorandom sequence
  526. // generators. The chi-square distribution is calculated for the stream
  527. // of bytes in the file and expressed as an absolute number and a
  528. // percentage which indicates how frequently a truly random sequence
  529. // would exceed the value calculated. We interpret the percentage as the
  530. // degree to which the sequence tested is suspected of being non-random.
  531. // If the percentage is greater than 99% or less than 1%, the sequence is
  532. // almost certainly not random. If the percentage is between 99% and 95%
  533. // or between 1% and 5%, the sequence is suspect. Percentages between 90%
  534. // and 95% and 5% and 10% indicate the sequence is "almost suspect".
  535. // Note that our JPEG file, while very dense in information, is far from
  536. // random as revealed by the chi-square test.
  537. //
  538. // Applying this test to the output of various pseudorandom sequence
  539. // generators is interesting. The low-order 8 bits returned by the
  540. // standard Unix rand() function, for example, yields:
  541. // Chi square distribution for 500000 samples is 0.01, and randomly
  542. // would exceed this value 99.99 percent of the times.
  543. //
  544. // While an improved generator [Park & Miller] reports:
  545. // Chi square distribution for 500000 samples is 212.53, and randomly
  546. // would exceed this value 95.00 percent of the times.
  547. //
  548. // Thus, the standard Unix generator (or at least the low-order bytes
  549. // it returns) is unacceptably non-random, while the improved generator
  550. // is much better but still sufficiently non-random to cause concern for
  551. // demanding applications. Contrast both of these software generators
  552. // with the chi-square result of a genuine random sequence created by
  553. // timing radioactive decay events.
  554. // Chi square distribution for 32768 samples is 237.05, and randomly
  555. // would exceed this value 75.00 percent of the times.
  556. //
  557. // See [Knuth, pp. 35-40] for more information on the chi-square test.
  558. // An interactive chi-square calculator is available at this site.
  559. //
  560. // Arithmetic Mean
  561. // This is simply the result of summing the all the bytes (bits if the -b
  562. // option is specified) in the file and dividing by the file length.
  563. // If the data are close to random, this should be about 127.5 (0.5 for -b
  564. // option output). If the mean departs from this value, the values are
  565. // consistently high or low.
  566. //
  567. // Monte Carlo Value for Pi
  568. // Each successive sequence of six bytes is used as 24 bit X and Y
  569. // co-ordinates within a square. If the distance of the randomly-generated
  570. // point is less than the radius of a circle inscribed within the square,
  571. // the six-byte sequence is considered a "hit". The percentage of hits can
  572. // be used to calculate the value of Pi. For very large streams
  573. // (this approximation converges very slowly), the value will approach the
  574. // correct value of Pi if the sequence is close to random. A 32768 byte
  575. // file created by radioactive decay yielded:
  576. // Monte Carlo value for Pi is 3.139648438 (error 0.06 percent).
  577. //
  578. // Serial Correlation Coefficient
  579. // This quantity measures the extent to which each byte in the file
  580. // depends upon the previous byte. For random sequences, this value
  581. // (which can be positive or negative) will, of course, be close to zero.
  582. // A non-random byte stream such as a C program will yield a serial
  583. // correlation coefficient on the order of 0.5. Wildly predictable data
  584. // such as uncompressed bitmaps will exhibit serial correlation coefficients
  585. // approaching 1. See [Knuth, pp. 64-65] for more details.
  586. ///////////////////////////////////////////////////////////////////////////////
  587. #define RFALSE 0
  588. #define RTRUE 1
  589. #define BINARY_MODE RTRUE
  590. #define BYTE_MODE RFALSE
  591. #define MONTEN 6 /* Bytes used as Monte Carlo co-ordinates. This should be no more bits than the mantissa of your "double" floating point type. */
  592. #define log2of10 3.32192809488736234787
  593. static int binary = RFALSE; /* Treat input as a bitstream */
  594. static long ccount[256]; /* Bins to count occurrences of values */
  595. static long totalc = 0; /* Total bytes counted */
  596. static double prob[256]; /* Probabilities per bin for entropy */
  597. static int mp, sccfirst;
  598. static unsigned int monte[MONTEN];
  599. static long inmont, mcount;
  600. static double cexp, incirc, montex, montey, montepi, scc, sccun, sccu0, scclast, scct1, scct2, scct3, ent, chisq, datasum;
  601. /* LOG2 -- Calculate log to the base 2 */
  602. static double Local_log2(double x)
  603. {
  604. return log2of10 * log10(x);
  605. }
  606. /* RT_INIT -- Initialise random test counters. Call with BINARY_MODE or BYTE_MODE */
  607. void rt_init(int binmode)
  608. {
  609. int i;
  610. binary = binmode; /* Set binary / byte mode */
  611. /* Initialise for calculations */
  612. ent = 0.0; /* Clear entropy accumulator */
  613. chisq = 0.0; /* Clear Chi-Square */
  614. datasum = 0.0; /* Clear sum of bytes for arithmetic mean */
  615. mp = 0; /* Reset Monte Carlo accumulator pointer */
  616. mcount = 0; /* Clear Monte Carlo tries */
  617. inmont = 0; /* Clear Monte Carlo inside count */
  618. incirc = 65535.0 * 65535.0; /* In-circle distance for Monte Carlo */
  619. sccfirst = RTRUE; /* Mark first time for serial correlation */
  620. scct1 = scct2 = scct3 = 0.0; /* Clear serial correlation terms */
  621. incirc = pow(pow(256.0, (double) (MONTEN / 2)) - 1, 2.0);
  622. for (i = 0; i < 256; i++) {
  623. ccount[i] = 0;
  624. }
  625. totalc = 0;
  626. }
  627. /* RT_ADD -- Add one or more bytes to accumulation. */
  628. void rt_add(void* buf, int bufl)
  629. {
  630. unsigned char* bp =(unsigned char*)buf;
  631. int oc, c, bean;
  632. while (bean = 0, (bufl-- > 0))
  633. {
  634. oc = *bp++;
  635. do {
  636. if (binary) {
  637. c = !!(oc & 0x80);
  638. }
  639. else {
  640. c = oc;
  641. }
  642. ccount[c]++; /* Update counter for this bin */
  643. totalc++;
  644. /* Update inside / outside circle counts for Monte Carlo computation of PI */
  645. if (bean == 0) {
  646. monte[mp++] = (unsigned int)oc; /* Save character for Monte Carlo */
  647. if (mp >= MONTEN) { /* Calculate every MONTEN character */
  648. int mj;
  649. mp = 0;
  650. mcount++;
  651. montex = montey = 0;
  652. for (mj = 0; mj < MONTEN / 2; mj++) {
  653. montex = (montex * 256.0) + monte[mj];
  654. montey = (montey * 256.0) + monte[(MONTEN / 2) + mj];
  655. }
  656. if ((montex * montex + montey * montey) <= incirc) {
  657. inmont++;
  658. }
  659. }
  660. }
  661. /* Update calculation of serial correlation coefficient */
  662. sccun = (double)c;
  663. if (sccfirst) {
  664. sccfirst = RFALSE;
  665. scclast = 0;
  666. sccu0 = sccun;
  667. }
  668. else {
  669. scct1 = scct1 + scclast * sccun;
  670. }
  671. scct2 = scct2 + sccun;
  672. scct3 = scct3 + (sccun * sccun);
  673. scclast = sccun;
  674. oc <<= 1;
  675. } while (binary && (++bean < 8));
  676. }
  677. }
  678. /* RT_END -- Complete calculation and return results. */
  679. void rt_end(double* r_ent, double* r_chisq, double* r_mean,
  680. double* r_montepicalc, double* r_scc)
  681. {
  682. int i;
  683. double a;
  684. /* Complete calculation of serial correlation coefficient */
  685. scct1 = scct1 + scclast * sccu0;
  686. scct2 = scct2 * scct2;
  687. scc = totalc * scct3 - scct2;
  688. if (scc == 0.0) {
  689. scc = -100000;
  690. }
  691. else {
  692. scc = (totalc * scct1 - scct2) / scc;
  693. }
  694. /* Scan bins and calculate probability for each bin and Chi-Square distribution */
  695. cexp = totalc / (binary ? 2.0 : 256.0); /* Expected count per bin */
  696. for (i = 0; i < (binary ? 2 : 256); i++) {
  697. prob[i] = (double) ccount[i] / totalc;
  698. a = ccount[i] - cexp;
  699. chisq = chisq + (a * a) / cexp;
  700. datasum += ((double) i) * ccount[i];
  701. }
  702. /* Calculate entropy */
  703. for (i = 0; i < (binary ? 2 : 256); i++) {
  704. if (prob[i] > 0.0) {
  705. ent += prob[i] * Local_log2(1 / prob[i]);
  706. }
  707. }
  708. /* Calculate Monte Carlo value for PI from percentage of hits within the circle */
  709. montepi = 4.0 * (((double) inmont) / mcount);
  710. /* Return results through arguments */
  711. *r_ent = ent;
  712. *r_chisq = chisq;
  713. *r_mean = datasum / totalc;
  714. *r_montepicalc = montepi;
  715. *r_scc = scc;
  716. }
  717. ///////////////////////////////////////////////////////////////////////////////
  718. #if 0
  719. static double get_double()
  720. {
  721. return 1.0;
  722. }
  723. static double CalculateSqrm(double a, double b)
  724. {
  725. return ((a - b) * (a - b)) / b;
  726. }
  727. static double CalculatePhi(double x)
  728. {
  729. static const double v[15] =
  730. {
  731. 1.2533141373155, .6556795424187985, .4213692292880545,
  732. .3045902987101033, .2366523829135607, .1928081047153158,
  733. .1623776608968675, .1401041834530502, .1231319632579329,
  734. .1097872825783083, .09902859647173193, .09017567550106468,
  735. .08276628650136917, .0764757610162485, .07106958053885211
  736. };
  737. // Local variables
  738. double cphi, a, b, h;
  739. double z, sum, pwr;
  740. int i, j;
  741. if (fabs(x) > 7.0)
  742. {
  743. if (x >= 0.0)
  744. return 1.0;
  745. return 0.0;
  746. }
  747. if (x>=0.0)
  748. cphi = 0.0;
  749. else
  750. cphi = 1.0;
  751. j = (int) (fabs(x) + 0.5);
  752. j = std::min<int>(j, 14);
  753. z = (double) j;
  754. h = fabs(x) - z;
  755. a = v[j];
  756. b = z * a - 1.0;
  757. pwr = 1.0;
  758. sum = a + h * b;
  759. for (i = 2; i <= (24-j); i += 2)
  760. {
  761. a = (a + z * b) / i;
  762. b = (b + z * a) / (i + 1);
  763. pwr *= h * h;
  764. sum += pwr * (a + h * b);
  765. }
  766. cphi = sum * exp(x * -0.5 * x - 0.918938533204672);
  767. if (x < 0.0)
  768. return cphi;
  769. return 1.0 - cphi;
  770. }
  771. static double CalculateChisq(double x, int n)
  772. {
  773. // System generated locals
  774. double ret_val;
  775. // Local variables
  776. double d;
  777. long i, l;
  778. double s, t;
  779. double xmin;
  780. if (x <= 0.0)
  781. return 0.0;
  782. if (n > 20)
  783. {
  784. t = (pow( x / n, 0.33333) - 1.0 + 0.22222 / n) / sqrt(0.22222 / n);
  785. return CalculatePhi(std::min(t, 8.0));
  786. }
  787. l = 4 - n % 2;
  788. d = (double) std::min(1, n / 3);
  789. ret_val = 0.0;
  790. for (i = l; i <= n; i += 2)
  791. {
  792. d = d * x / (i - 2);
  793. ret_val += d;
  794. }
  795. xmin = std::min(x * 0.5, 50.0);
  796. if (l == 3)
  797. {
  798. s = sqrt( xmin );
  799. return CalculatePhi(s/0.7071068) - exp(-xmin) * 0.564189 * ret_val / s;
  800. }
  801. return 1.0 - exp(-xmin) * (ret_val + 1.0);
  802. }
  803. ///////////////////////////////////////////////////////////////////////////////
  804. // TestCraps
  805. //
  806. // This is the Craps test. It plays 200,000 games of craps, finds
  807. // the number of wins and the number of throws necessary to end
  808. // each game. The number of wins should be (very close to) a
  809. // normal with mean 200000p and variance 200000p(1 - p), with
  810. // p = 244 / 495. Throws necessary to complete the game can vary
  811. // from 1 to infinity, but counts for all > 21 are lumped with 21.
  812. // A chi-square test is made on the #-of-throws cell counts.
  813. // Each 32-bit integer from the test file provides the value for
  814. // the throw of a die, by floating to [0, 1), multiplying by 6
  815. // and taking 1 plus the integer part of the result.
  816. //
  817. static void TestCraps(double& pvalueWins, double& pvalueThrows)
  818. {
  819. static long nt[22];
  820. static double e[22];
  821. double t;
  822. double pwins;
  823. double av; // Expected win count.
  824. double sd;
  825. double ex;
  826. double sum;
  827. long ng;
  828. long gc;
  829. long nwins; // Actual win count.
  830. double pthrows;
  831. int nthrows;
  832. int point;
  833. int i, m, k;
  834. e[1] = 1.0 / 3.0;
  835. sum = e[1];
  836. for (k = 2; k <= 20; ++k)
  837. {
  838. e[k] = ( pow(27.0/36.0, (double) k-2) * 27.0 +
  839. pow(26.0/36.0, (double) k-2) * 40.0 +
  840. pow(25.0/36.0, (double) k-2) * 55.0 ) / 648.0;
  841. sum += e[k];
  842. }
  843. e[21] = 1.0 - sum;
  844. ng = 200000;
  845. nwins = 0;
  846. for (i = 1; i <= 21; ++i)
  847. nt[i] = 0;
  848. for (gc = 1; gc <= ng; ++gc)
  849. {
  850. point = (int)(get_double() * 6.0) + (int)(get_double() * 6.0) + 2;
  851. nthrows = 1;
  852. if ((point == 7) || (point == 11))
  853. ++nwins;
  854. else if ((point != 2) && (point != 3) && (point != 12))
  855. {
  856. for(;;)
  857. {
  858. ++nthrows;
  859. k = (int)(get_double() * 6.0) + (int)(get_double() * 6.0) + 2;
  860. if (k == 7)
  861. break;
  862. if (k == point)
  863. {
  864. ++nwins;
  865. break;
  866. }
  867. }
  868. }
  869. m = std::min<int>(21, nthrows);
  870. ++nt[m];
  871. }
  872. av = ng * 244.0 / 495.0;
  873. sd = sqrt(av * 251.0 / 495.0);
  874. t = (nwins - av) / sd;
  875. //dprintf(" Results of craps test for %s\n", filename);
  876. //dprintf(" No. of wins: Observed Expected\n");
  877. //dprintf(" %9ld %11.2f\n", nwins, av);
  878. pwins = CalculatePhi(t);
  879. //dprintf(" %8ld= No. of wins, z-score=%6.3f pvalue=%7.5f\n", nwins, t, pwins);
  880. //dprintf(" Analysis of Throws-per-Game:\n");
  881. sum = 0.0;
  882. for (i = 1; i <= 21; ++i)
  883. {
  884. ex = ng * e[i];
  885. sum += CalculateSqrm((double)nt[i], ex);
  886. }
  887. pthrows = CalculateChisq(sum, 20);
  888. //dprintf(" Chisq=%7.2f for 20 degrees of freedom, p=%8.5f\n", sum, pthrows);
  889. //dprintf(" Throws Observed Expected Chisq Sum\n");
  890. //sum = 0.0;
  891. //for (i = 1; i <= 21; ++i)
  892. //{
  893. // ex = ng * e[i];
  894. // t = sqrm((double)nt[i], ex);
  895. // sum += t;
  896. //
  897. // dprintf("%19d %8ld %10.1f %7.3f %8.3f\n", i, nt[i], ex, t, sum);
  898. //}
  899. //save_pvalue(pwins);
  900. //save_pvalue(pthrows);
  901. //dprintf(" SUMMARY FOR %s\n", filename);
  902. //dprintf(" p-value for no. of wins:%8.6f\n", pwins);
  903. //dprintf(" p-value for throws/game:%8.6f\n", pthrows);
  904. pvalueWins = pwins;
  905. pvalueThrows = pthrows;
  906. }
  907. #endif
  908. #ifdef _MSC_VER
  909. #pragma warning(pop)
  910. #endif