Advertisement
Guest User

zadania z monte carlo

a guest
Oct 14th, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. // ConsoleApplication1.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <cmath>
  6. #include <random>
  7. #include <chrono>
  8. #include <iostream>
  9.  
  10. using namespace std;
  11.  
  12.  
  13. class Point2D
  14. {
  15. private:
  16.  
  17.     float x_co;
  18.  
  19.     float y_co;
  20. public:
  21.     Point2D(float  x = 0, float  y = 0) : x_co{ x }, y_co{ y }
  22.     {}
  23.  
  24.     float get_x() const { return x_co; }
  25.     float get_y() const { return y_co; }
  26.  
  27.  
  28. };
  29. class Circle{
  30.     Point2D m_middle;
  31.     float r;
  32. public:
  33.     Circle(const Point2D& middle = Point2D(), float rr = 1) : m_middle{ middle }, r{ rr }
  34.     {}
  35.     bool is_inside(const Point2D& p){
  36.         return sqrt((m_middle.get_x() - p.get_x())*(m_middle.get_x() - p.get_x()) + (m_middle.get_y() - p.get_y())*(m_middle.get_y() - p.get_y())) < r;
  37.     }
  38. };
  39.  
  40.  
  41. int main(){
  42.     mt19937 gen{ (unsigned int)chrono::system_clock::now().time_since_epoch().count() };
  43.     uniform_real_distribution<double> distribution{ -1.0, 1.0 };
  44.  
  45.     const int n = 1e6;
  46.     float ni = 0.0;
  47.     float pole_kwadratu = 4;
  48.     Circle carlo;
  49.  
  50.     for (int i = 0; i < n; ++i) {
  51.         Point2D k(distribution(gen), distribution(gen));
  52.         if (carlo.is_inside(k) == true){
  53.             ni++;          
  54.         }
  55.     }
  56.  
  57.     cout << (ni / n)*pole_kwadratu << endl;
  58.  
  59.  
  60.     system("pause");
  61.  
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement