fork download
  1. #include <stdlib.h>
  2. #include <math.h>
  3. #include <time.h>
  4. #include <iostream>
  5. #include <vector>
  6.  
  7. static bool isGet(int captureProbability)
  8. {
  9. const int r = rand() % 100;
  10. return r < captureProbability;
  11. }
  12.  
  13. int main()
  14. {
  15. const int probablility = 12; /*捕獲率*/
  16. const int captureNum = 50; /*1セット捕獲率*/
  17. const int trialNum = 10000; /*試行回数*/
  18.  
  19. srand(time(0));
  20.  
  21. std::vector<int> data(trialNum);
  22. for(int i = 0 ; i < trialNum ; ++i)
  23. {
  24. int capture = 0;
  25. for(int j = 0 ; j < captureNum ; ++j)
  26. {
  27. if(isGet(probablility))
  28. ++capture;
  29. }
  30. data[i] = capture;
  31. }
  32.  
  33. int sum = 0;
  34. for(int i = 0 ; i < trialNum ; ++i)
  35. {
  36. sum += data[i];
  37. }
  38. const double average = static_cast<double>(sum) / static_cast<double>(trialNum);
  39.  
  40. double scattering = 0.0;
  41. for(int i = 0 ; i < trialNum ; ++i)
  42. {
  43. const double dif = average - static_cast<double>(data[i]);
  44. scattering += dif * dif;
  45. }
  46. scattering /= trialNum;
  47.  
  48. const double standardDeviation = sqrt(scattering);
  49.  
  50. std::cout << "捕獲率12%のモンスターを50匹倒したとき、" << std::endl;
  51. std::cout << "68%の確率で、" << average - standardDeviation << "~" << average + standardDeviation << "匹捕獲できる" << std::endl;
  52. std::cout << "95%の確率で、" << average - standardDeviation * 2.0 << "~" << average + standardDeviation * 2.0 << "匹捕獲できる" << std::endl;
  53.  
  54. return 0;
  55. }
  56.  
Success #stdin #stdout 0.03s 2856KB
stdin
Standard input is empty
stdout
捕獲率12%のモンスターを50匹倒したとき、
68%の確率で、3.68787~8.26713匹捕獲できる
95%の確率で、1.39825~10.5568匹捕獲できる