Advertisement
daniv1

Untitled

Nov 24th, 2021
855
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. double f(double x)
  8. {
  9.     return 1.0 / (1.0 + x + pow(x,2));
  10. }
  11.  
  12. double getRandomValue(double min, double max)
  13. {
  14.     double f = (double)rand() / RAND_MAX;
  15.     return min + f * (max - min);
  16. }
  17.  
  18.  
  19. double monteCarlo(double a, double b, int N)
  20. {
  21.     std::vector<double> xi(N), yi(N);
  22.  
  23.     double step = (b - a) / N;
  24.  
  25.     double MMax = 0;
  26.     for (double i = a; i <= b; i += step)
  27.     {
  28.         if (f(i) > MMax)
  29.             MMax = f(i);
  30.     }
  31.  
  32.     int Ncounter = 0;
  33.  
  34.     double S = (b - a) * MMax;
  35.  
  36.     for (size_t i = 0; i < xi.size(); ++i)
  37.     {
  38.         xi[i] = a + getRandomValue(0, 1) * (b - a);
  39.         yi[i] = f(xi[i]);
  40.  
  41.         double Y = getRandomValue(0, 1) * MMax;
  42.         if ( Y <= yi[i] )
  43.             Ncounter++;
  44.     }
  45.  
  46.     return S * Ncounter / static_cast<double>(N);
  47. }
  48. int main()
  49. {
  50.     cout << monteCarlo(0.0, 1.0, 5000) << endl;
  51.     return 0;
  52. }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement