forked from 1chipML/1chipML
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmc_std.c
70 lines (47 loc) · 1.62 KB
/
mc_std.c
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
69
70
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
double myFunction(double x);
void monteCarloEstimateSTD(double lowBound, double upBound, int iterations,
double mcStats[]);
int main() {
double lowerBound, upperBound;
int iterations;
lowerBound = 1;
upperBound = 5;
double mcStats[2]; // position 0 holds the estimate, position 1 holds the STD
for (int i = 1; i < 6; i++) {
iterations = 2 * pow(4, i);
monteCarloEstimateSTD(lowerBound, upperBound, iterations, mcStats);
printf("Estimate for %.1f -> %.1f is %.3f, STD = %.4f, (%i iterations)\n",
lowerBound, upperBound, mcStats[0], mcStats[1], iterations);
}
return 0;
}
double myFunction(double x)
// Function to integrate
{
return pow(x, 4) * exp(-x);
}
void monteCarloEstimateSTD(double lowBound, double upBound, int iterations,
double statsArray[])
// Function to execute Monte Carlo integration on predefined function
{
double totalSum = 0;
double totalSumSquared = 0;
int iter = 0;
while (iter < iterations - 1) {
double randNum = lowBound + (float)rand() / RAND_MAX * (upBound - lowBound);
double functionVal = myFunction(randNum);
totalSum += functionVal;
totalSumSquared += pow(functionVal, 2);
iter++;
}
double estimate = (upBound - lowBound) * totalSum / iterations;
double expected = totalSum / iterations;
double expectedSquare = totalSumSquared / iterations;
double std = (upBound - lowBound) *
pow((expectedSquare - pow(expected, 2)) / (iterations - 1), 0.5);
statsArray[0] = estimate;
statsArray[1] = std;
}