RandomTests.cpp 2.0 KB

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