Code:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
double f(double x);
double monteCarlo(double a, double b, double yMin, double yMax, int trials);
double expectedDoubles(void);
double randDouble(double min, double max);
struct Data {
float time;
float accel;
};
void printItem(struct Data pi);
const int MAX = 100;
struct Data points[MAX];
void main(int argc, char* argv[])
{
int count;
int i = 0;
double v;
int steps = 10000;
int a, b, yMin, yMax;
//printf("How many items? ");
//scanf("%d", &count);
////Enter in the data, Time = 0 means quit
printf("Enter in all data, time = 0 to quit.\n");
count = 0;
do {
printf("Time? ");
scanf("%f", &points[i].time);
printf("Accel? ");
scanf("%f", &points[i].accel);
++count;
} while (points[i].time != 0);
//for (i = 0; i < count; ++i) {
// printf("Time? ");
// scanf("%f", &points[i].time);
// printf("Accel? ");
// scanf("%f", &points[i].accel);
//}
//Print out the data points
/*printf("\n\nPrinting Data Points\n");
for (i = 0; i < count; ++i) {
printItem(points[i]);*/
//}
//Find a,b,yMin,yMax ==> Starting data point is assumed to be 0,0
a = 0;
b = points[0].time;
yMin = 0;
yMax = points[0].accel;
for (i = 1; i < count; ++i) {
if(points[i].time > b){
b = points[i].time;
}
if(points[i].accel > yMax){
yMax = points[i].accel;
}
}
//Print resulting Velocity
//Data check
/*printf("%d, %d, %d, %d\n",a,b,yMin,yMax);*/
v = monteCarlo(a, b, yMin, yMax, steps);
printf("Velocity = %.3f [m/s]\n", v);
getchar();
getchar();
}
void printItem(struct Data dp) {
printf("Time: %.2f\n", dp.time);
printf("Accel: %.2f\n", dp.accel);
printf("\n\n");
}
double f(double x) { //function to be integrated
double v;
//Vf = V0 + a * t
v = 0 + x; //v0 starts at 0 according to the problem & at is replaced by x here
return v;
}
double monteCarlo(double a, double b, double yMin, double yMax, int trials) {
double boundryArea = (b - a) * (yMax - yMin);
int trial;
double randX, randY;
int hits = 0;
srand(time(0));
for (trial = 0; trial < trials; ++trial) {
randX = randDouble(a, b);
randY = randDouble(yMin, yMax);
if (f(randX) >= 0 && randX >= 0 && randY < f(randX)) {
++hits;
} else if (f(randX) < 0 && randY < 0 && randY > f(randX)) {
++hits;
}
}
return (hits / (double) trials) * boundryArea;
}
double randDouble(double min, double max) {
double r = rand() / (double) (RAND_MAX + 1);
return r * (max - min) + min;
}
double expectedDoubles(void) {
const int TRIALS = 10000;
int trial;
int die1;
int die2;
int rolls;
int totalRolls = 0;
for (trial = 0; trial < TRIALS; ++trial) {
rolls = 0;
do {
die1 = rand() % 6 + 1;
die2 = rand() % 6 + 1;
++rolls;
} while (die1 != die2);
totalRolls += rolls;
}
return (double)totalRolls / TRIALS;
}