RandomTests.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include "../Tests.hpp"
  2. #include "core/data/Array.hpp"
  3. #include "core/utils/Random.hpp"
  4. static void testAverage(bool light) {
  5. int limit = light ? 100000 : 1000000;
  6. Core::Random r(553);
  7. float sum = 0;
  8. for(int i = 0; i < limit; i++) {
  9. sum += static_cast<float>(r.next(2, 10));
  10. }
  11. sum /= static_cast<float>(limit);
  12. CORE_TEST_FLOAT(6.0f, sum, 0.01f);
  13. }
  14. static void testCoin(bool light) {
  15. int limit = light ? 100000 : 1000000;
  16. Core::Random r(553);
  17. Core::Array<int, 2> c(0);
  18. for(int i = 0; i < limit; i++) {
  19. c[r.nextBool()]++;
  20. }
  21. CORE_TEST_FLOAT(0.0f,
  22. static_cast<float>(c[0] - c[1]) / static_cast<float>(limit),
  23. 0.003f);
  24. }
  25. static void testDistribution(bool light) {
  26. int limit = light ? 100000 : 1000000;
  27. Core::Random r(553);
  28. Core::Array<int, 102> c(0);
  29. for(int i = 0; i < limit; i++) {
  30. c[r.next(1, c.getLength() - 2)]++;
  31. }
  32. CORE_TEST_EQUAL(0, c[0]);
  33. CORE_TEST_EQUAL(0, c[c.getLength() - 1]);
  34. for(int i = 1; i < c.getLength() - 1; i++) {
  35. CORE_TEST_FLOAT(0.01f,
  36. static_cast<float>(c[i]) / static_cast<float>(limit),
  37. 0.001f);
  38. }
  39. }
  40. static void testFloatAverage(bool light) {
  41. int limit = light ? 100000 : 1000000;
  42. Core::Random r(553);
  43. float sum = 0;
  44. for(int i = 0; i < limit; i++) {
  45. sum += r.nextFloat();
  46. }
  47. sum /= static_cast<float>(limit);
  48. CORE_TEST_FLOAT(0.5f, sum, 0.001f);
  49. }
  50. static void testFloatCoin(bool light) {
  51. int limit = light ? 100000 : 1000000;
  52. Core::Random r(553);
  53. Core::Array<int, 2> c(0);
  54. for(int i = 0; i < limit; i++) {
  55. c[r.nextFloat() < 0.5f]++;
  56. }
  57. CORE_TEST_FLOAT(0.0f,
  58. static_cast<float>(c[0] - c[1]) / static_cast<float>(limit),
  59. 0.003f);
  60. }
  61. static void testFloatDistribution(bool light) {
  62. int limit = light ? 100000 : 1000000;
  63. Core::Random r(553);
  64. Core::Array<int, 102> c(0);
  65. for(int i = 0; i < limit; i++) {
  66. c[static_cast<int>(r.nextFloat(1.0f, c.getLength() - 1))]++;
  67. }
  68. CORE_TEST_EQUAL(0, c[0]);
  69. CORE_TEST_EQUAL(0, c[c.getLength() - 1]);
  70. for(int i = 1; i < c.getLength() - 1; i++) {
  71. CORE_TEST_FLOAT(0.01f,
  72. static_cast<float>(c[i]) / static_cast<float>(limit),
  73. 0.003f);
  74. }
  75. }
  76. void Core::testRandom(bool light) {
  77. testAverage(light);
  78. testCoin(light);
  79. testDistribution(light);
  80. testFloatAverage(light);
  81. testFloatCoin(light);
  82. testFloatDistribution(light);
  83. }