RandomTests.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #include "../Tests.h"
  2. #include "core/Random.h"
  3. static void testAverage(bool light) {
  4. int limit = light ? 100000 : 1000000;
  5. Random r;
  6. initRandom(&r, 553);
  7. float sum = 0;
  8. for(int i = 0; i < limit; i++) {
  9. u32 u = randomU32(&r, 2, 11);
  10. sum += (float)u;
  11. }
  12. sum /= (float)limit;
  13. TEST_FLOAT(6.0f, sum, 0.01f);
  14. }
  15. static void testCoin(bool light) {
  16. int limit = light ? 100000 : 1000000;
  17. Random r;
  18. initRandom(&r, 5533);
  19. int c[2] = {0, 0};
  20. for(int i = 0; i < limit; i++) {
  21. c[randomBool(&r)]++;
  22. }
  23. TEST_FLOAT(0.0f, (float)(c[0] - c[1]) / (float)limit, 0.003f);
  24. }
  25. static void testDistribution(bool light) {
  26. size_t limit = light ? 100000 : 1000000;
  27. Random r;
  28. initRandom(&r, 553);
  29. int c[102] = {0};
  30. for(size_t i = 0; i < limit; i++) {
  31. c[randomSize(&r, 1, 101)]++;
  32. }
  33. TEST_INT(0, c[0]);
  34. TEST_INT(0, c[101]);
  35. for(size_t i = 1; i < 101; i++) {
  36. TEST_FLOAT(0.01f, (float)c[i] / (float)limit, 0.001f);
  37. }
  38. }
  39. static void testFloatAverage(bool light) {
  40. int limit = light ? 100000 : 1000000;
  41. Random r;
  42. initRandom(&r, 553);
  43. float sum = 0;
  44. for(int i = 0; i < limit; i++) {
  45. sum += randomFloat(&r);
  46. }
  47. sum /= (float)limit;
  48. TEST_FLOAT(0.5f, sum, 0.001f);
  49. }
  50. static void testFloatCoin(bool light) {
  51. int limit = light ? 100000 : 1000000;
  52. Random r;
  53. initRandom(&r, 5534);
  54. int c[2] = {0, 0};
  55. for(int i = 0; i < limit; i++) {
  56. c[randomFloat(&r) < 0.5f]++;
  57. }
  58. TEST_FLOAT(0.0f, (float)(c[0] - c[1]) / (float)limit, 0.003f);
  59. }
  60. static void testFloatDistribution(bool light) {
  61. int limit = light ? 100000 : 1000000;
  62. Random r;
  63. initRandom(&r, 553);
  64. int c[102] = {0};
  65. for(int i = 0; i < limit; i++) {
  66. c[(size_t)(1.0f + randomFloat(&r) * 100.0f)]++;
  67. }
  68. TEST_INT(0, c[0]);
  69. TEST_INT(0, c[101]);
  70. for(size_t i = 1; i < 101; i++) {
  71. TEST_FLOAT(0.01f, (float)c[i] / (float)limit, 0.003f);
  72. }
  73. }
  74. static void testRandomI32() {
  75. Random r;
  76. initRandom(&r, 56346);
  77. int c[7] = {0};
  78. for(int i = 0; i < 10000; i++) {
  79. i32 index = randomI32(&r, -2, 3) + 3;
  80. if(TEST_TRUE(index >= 0 && index < 7)) {
  81. c[index]++;
  82. }
  83. }
  84. for(size_t i = 0; i < 7; i++) {
  85. TEST_BOOL(i != 0 && i != 6, c[i] > 0);
  86. }
  87. }
  88. void testRandom(bool light) {
  89. testAverage(light);
  90. testCoin(light);
  91. testDistribution(light);
  92. testFloatAverage(light);
  93. testFloatCoin(light);
  94. testFloatDistribution(light);
  95. testRandomI32();
  96. }