Advertisement
grosul

Untitled

May 16th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.20 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <random>
  4. #include <fstream>
  5.  
  6. class MonteCarlo{
  7. public:
  8.     MonteCarlo(double begin,
  9.             double end,
  10.             size_t number,
  11.             std::function<double(double)> function,
  12.             std::function<double(double)> antiderivative) :
  13.             begin_(begin), end_(end), number_(number),
  14.             function_(function), antiderivative_(antiderivative), result_(0) {}
  15.  
  16.  
  17.     void Calculate() {
  18.       std::random_device rd;
  19.       std::mt19937 gen(rd());
  20.       std::uniform_real_distribution<> dis(begin_, end_);
  21.  
  22.       for (size_t i = 0; i < number_; ++i) {
  23.         result_ += function_(dis(gen));
  24.       }
  25.  
  26.  
  27.       result_ *= (end_ - begin_)/number_;
  28.       true_result_ = antiderivative_(end_) - antiderivative_(begin_);
  29.       difference_ = fabs(true_result_ - result_);
  30.     }
  31.  
  32.     double GetResult() {
  33.       if (!calculated_) {
  34.         Calculate();
  35.         calculated_ = true;
  36.       }
  37.  
  38.       return result_;
  39.     }
  40.  
  41.     double GetDiff() {
  42.       if (!calculated_) {
  43.         Calculate();
  44.         calculated_ = true;
  45.       }
  46.  
  47.       return difference_;
  48.     }
  49.  
  50.     double GetTrueResult() {
  51.       if (!calculated_) {
  52.         Calculate();
  53.         calculated_ = true;
  54.       }
  55.  
  56.       return true_result_;
  57.     }
  58.  
  59. private:
  60.     double begin_;
  61.     double end_;
  62.     size_t number_;
  63.     std::function<double(double)> function_;
  64.     std::function<double(double)> antiderivative_;
  65.  
  66.     bool calculated_;
  67.  
  68.     double result_;
  69.     double true_result_;
  70.     double difference_;
  71. };
  72.  
  73.  
  74. double func(double x) {
  75.   return cos(x);
  76. }
  77.  
  78. double antiderivative(double x) {
  79.   return sin(x);
  80. }
  81.  
  82.  
  83. int main() {
  84.   auto file_name = "result.txt";
  85.   std::ofstream file;
  86.   file.open(file_name);
  87.   for (int exp_num = 1; exp_num < 100; ++exp_num) {
  88.     auto MCcalc = MonteCarlo(
  89.             /* начало = У*/ 0,
  90.             /* конец = */ 3,
  91.             /* количество точек = */ 10000,
  92.             /* функция = */ func,
  93.             /* первообразная = */ antiderivative);
  94.  
  95.     MCcalc.Calculate();
  96.     file << exp_num << ' ' << MCcalc.GetDiff() << std::endl;
  97.   }
  98.  
  99.   file.close();
  100.   return 0;
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement