-
Notifications
You must be signed in to change notification settings - Fork 0
/
1-montecarlo(winapi).cpp
68 lines (56 loc) · 1.03 KB
/
1-montecarlo(winapi).cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
#include <ctime>
#include <math.h>
#include <windows.h>
using namespace std;
double a,b;
double I,S,x,y,f;
int K,N;
const int numThreads = 2;
HANDLE h[numThreads];
CRITICAL_SECTION cs;
double func(double xx)
{
double ff = xx*xx + 3;
return ff;
}
DWORD WINAPI ThreadFunc(LPVOID lp)
{
int temp = 0;
for(int i=0; i<=N/numThreads; i++)
{
x = a*abs(double(rand())/RAND_MAX);
y = b*abs(double(rand())/RAND_MAX);
f = func(x);
if (y<=f) temp++;
}
EnterCriticalSection(&cs);
K += temp;
LeaveCriticalSection(&cs);
return 0;
}
void MonteKarlo(int K)
{
for(int i = 0; i<numThreads; i++)
h[i] = CreateThread(0,0,ThreadFunc,0,0,0);
WaitForMultipleObjects(numThreads,h,true,INFINITE);
}
void main()
{
InitializeCriticalSection(&cs);
cout<<"Input a = "; cin>>a;
clock_t time = clock();
b = func(a);
K = 0;
N = 100*1000*1000;
srand(time);
MonteKarlo(K);
S = a * b;
I = K*S/N;
cout<<"Integral = "<<I;
time = clock() - time;
cout<<" time = "<<time<<" msc\n";
DeleteCriticalSection(&cs);
int q;
cin>>q;
}