test_runs_test.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * Copyright Nick Thompson, 2019
  3. * Use, modification and distribution are subject to the
  4. * Boost Software License, Version 1.0. (See accompanying file
  5. * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. */
  7. #include "math_unit_test.hpp"
  8. #include <vector>
  9. #include <random>
  10. #include <boost/math/statistics/runs_test.hpp>
  11. using boost::math::statistics::runs_above_and_below_median;
  12. void test_agreement_with_r_randtests()
  13. {
  14. // $R
  15. // install.packages("randtests")
  16. // library(randtests)
  17. // earthden <- c(5.36, 5.29, 5.58, 5.65, 5.57, 5.53, 5.62, 5.29, 5.44, 5.34, 5.79,5.10, 5.27, 5.39, 5.42, 5.47, 5.63, 5.34, 5.46, 5.30, 5.75, 5.68, 5.85)
  18. // h = runs.test(earthden)
  19. // options(digits=18)
  20. //> h$statistic
  21. // -1.74772579501060576
  22. // > h$p.value
  23. // [1] 0.0805115199405023046
  24. // median of v is 5.46, 23 elements.
  25. std::vector<double> v{5.36, 5.29,
  26. 5.58, 5.65, 5.57, 5.53, 5.62,
  27. 5.29, 5.44, 5.34,
  28. 5.79, 5.10,
  29. 5.27, 5.39, 5.42,
  30. 5.47, 5.63,
  31. 5.34,
  32. 5.46, /* median */
  33. 5.30,
  34. 5.75, 5.68, 5.85};
  35. // v -> {-,-,+,+,+,+,+,-,-,-,+,+,-,-,-,+,+,-,-,+,+,+}, 8 runs.
  36. double expected_statistic = -1.74772579501060576;
  37. double expected_pvalue = 0.0805115199405023046;
  38. auto [computed_statistic, computed_pvalue] = runs_above_and_below_median(v);
  39. CHECK_ULP_CLOSE(expected_statistic, computed_statistic, 3);
  40. CHECK_ULP_CLOSE(expected_pvalue, computed_pvalue, 3);
  41. }
  42. void test_doc_example()
  43. {
  44. std::vector<double> v{5, 2, 0, 4, 7, 9, 10, 6, 1, 8, 3};
  45. double expected_statistic = -0.670820393249936919;
  46. double expected_pvalue = 0.502334954360502017;
  47. auto [computed_statistic, computed_pvalue] = runs_above_and_below_median(v);
  48. CHECK_ULP_CLOSE(expected_statistic, computed_statistic, 3);
  49. CHECK_ULP_CLOSE(expected_pvalue, computed_pvalue, 3);
  50. }
  51. void test_constant_vector()
  52. {
  53. std::vector<double> v{5,5,5,5,5,5,5};
  54. auto [computed_statistic, computed_pvalue] = runs_above_and_below_median(v);
  55. double expected_pvalue = 0;
  56. CHECK_ULP_CLOSE(expected_pvalue, computed_pvalue, 3);
  57. if (!std::isnan(computed_statistic)) {
  58. std::cerr << "Computed statistic is not a nan!\n";
  59. }
  60. }
  61. int main()
  62. {
  63. test_constant_vector();
  64. test_agreement_with_r_randtests();
  65. test_doc_example();
  66. return boost::math::test::report_errors();
  67. }