Advertisement
eitherlast

MonteCarlo

Dec 6th, 2017
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <time.h>
  3. #include "stdafx.h"
  4. #include <stdlib.h>
  5. #include <iostream>
  6.  
  7. using namespace std;
  8.  
  9. double Fun(double x) {
  10. return x*x;
  11. }
  12.  
  13. double MonteCarlo(double a, double b) {
  14.  
  15. srand(123975467);
  16. int countAll = 0;
  17. int countSquare = 0;
  18. double x;
  19. double y;
  20. double maxOfArea = (Fun(a) > Fun(b) ? Fun(a) : Fun(b));
  21.  
  22. for (int i = 0; i < 1000000; i++) {
  23. x = ((rand() % 10000) / 10000.0) * (b - a) + a;
  24. y = ((rand() % 10000) / 10000.0) * maxOfArea;
  25. countAll += 1;
  26. // printf("%lf %lf\n", x, y);
  27. if (y <= Fun(x)) { //y не больше х*х в данной точке
  28. countSquare = countSquare + 1;
  29. // printf("aaa");
  30. }
  31. }
  32. printf("%d\n", countSquare);
  33. printf("%d\n", countAll);
  34. printf("Integral equals to ");
  35.  
  36. double res = (b - a) * maxOfArea * countSquare / countAll;
  37. return res;
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement