The function does not have an antiderivative that can be expressed in terms of e
ID: 3556536 • Letter: T
Question
The function does not have an antiderivative that can be expressed in terms of elementary functions (ex, sin x, etc.), so the integral of this function must be estimated by some numerical technique. Approximate the integral by using the Monte Carlo Method we learned in class. The graph of the function is shown below: Hint: You need to include to calculate the e-x2 by using exp(-(x*x)). Sample Input/Output: Input in red color; output in black. Run again(l=yes,0=no)? 1 How many trials? 100 Integral = 0.720000 Run again(l=yes,0=no)? 1 How many trials? 10000 Integral = 0.746400 Run again(l=yes,0=no)? 1 How many trials? 1000000 Integral = 0.746515Explanation / Answer
http://pastebin.com/s3A1Q7MW
#include <cstdlib>
#include <cstdio>
#include <math.h>
#include <time.h>
using namespace std;
double monte(int trials) {
// Initialize the count to 0
int integral = 0;
for (int i=0; i<trials; ++i) {
// Get two random double values between 0 and 1
double x = rand() / (RAND_MAX * 1.0);
double y = rand() / (RAND_MAX * 1.0);
// Calculate the y value of the equation
double comp = exp(-(x * x));
// Check if your generated y value is underneath the line
if (y < comp) {
// Increment the hit amount
++integral;
}
}
// Return the ratio of hits / (hits + misses)
return (integral * 1.0) / trials;
}
int main() {
srand(time(NULL));
int ans, trials;
while (1) {
printf("Run again(1=yes,0=no)? ");
scanf("%i",&ans);
if (ans == 0) {
break;
}
printf(" How many trials? ");
scanf("%i",&trials);
double monte_trial_solution = monte(trials);
// %lf is printing a double
printf(" Integral = %lf ", monte_trial_solution);
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.