sample_variance.hpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // -*- C++ -*-
  2. // Copyright (C) 2005-2022 Free Software Foundation, Inc.
  3. //
  4. // This file is part of the GNU ISO C++ Library. This library is free
  5. // software; you can redistribute it and/or modify it under the terms
  6. // of the GNU General Public License as published by the Free Software
  7. // Foundation; either version 3, or (at your option) any later
  8. // version.
  9. // This library is distributed in the hope that it will be useful, but
  10. // WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. // General Public License for more details.
  13. // You should have received a copy of the GNU General Public License
  14. // along with this library; see the file COPYING3. If not see
  15. // <http://www.gnu.org/licenses/>.
  16. // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.
  17. // Permission to use, copy, modify, sell, and distribute this software
  18. // is hereby granted without fee, provided that the above copyright
  19. // notice appears in all copies, and that both that copyright notice
  20. // and this permission notice appear in supporting documentation. None
  21. // of the above authors, nor IBM Haifa Research Laboratories, make any
  22. // representation about the suitability of this software for any
  23. // purpose. It is provided "as is" without express or implied
  24. // warranty.
  25. /**
  26. * @file sample_variance.hpp
  27. * Contains a function for calculating a sample variance
  28. */
  29. #ifndef PB_DS_SAMPLE_VAR_HPP
  30. #define PB_DS_SAMPLE_VAR_HPP
  31. #include <list>
  32. #include <numeric>
  33. #include <math.h>
  34. #include <iterator>
  35. namespace __gnu_pbds
  36. {
  37. namespace test
  38. {
  39. namespace detail
  40. {
  41. #define PB_DS_VTYPE typename std::iterator_traits<It>::value_type
  42. template<typename It>
  43. PB_DS_VTYPE
  44. sample_variance(It b, It e, PB_DS_VTYPE sm)
  45. {
  46. PB_DS_VTYPE ss = 0;
  47. size_t num_res = 0;
  48. while (b != e)
  49. {
  50. const PB_DS_VTYPE d =* b - sm;
  51. ss += d* d;
  52. ++num_res;
  53. ++b;
  54. }
  55. if (num_res == 1)
  56. return 0;
  57. return ::sqrt(ss / (num_res - 1));
  58. }
  59. #undef PB_DS_VTYPE
  60. } // namespace detail
  61. } // namespace test
  62. } // namespace __gnu_pbds
  63. #endif