forked from 1chipML/1chipML
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmc_integration.c
57 lines (39 loc) · 1.21 KB
/
mc_integration.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
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
double myFunction(double x);
double monteCarloEstimate(double lowBound, double upBound, int iterations);
int main() {
double lowerBound, upperBound;
int iterations;
lowerBound = 1;
upperBound = 5;
iterations = 200;
double estimate = monteCarloEstimate(lowerBound, upperBound, iterations);
printf("Estimate for %.1f -> %.1f is %.2f, (%i iterations)\n", lowerBound,
upperBound, estimate, iterations);
return 0;
}
double myFunction(double x)
// Function to integrate
{
return pow(x, 4) * exp(-x);
}
double monteCarloEstimate(double lowBound, double upBound, int iterations)
// Function to execute Monte Carlo integration on predefined function
{
double totalSum = 0;
double randNum, functionVal;
int iter = 0;
while (iter < iterations - 1) {
// Select a random number within the limits of integration
randNum = lowBound + (float)rand() / RAND_MAX * (upBound - lowBound);
// Sample the function's values
functionVal = myFunction(randNum);
// Add the f(x) value to the running sum
totalSum += functionVal;
iter++;
}
double estimate = (upBound - lowBound) * totalSum / iterations;
return estimate;
}