RandomTests.cpp 2.0 KB

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