Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The function e -x^2 does not have an antiderivative that can be expressed in ter

ID: 3556531 • Letter: T

Question

The function e-x^2 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. (remember that integral is the areaunderneath the line )

Hint: You need to include <math.h> to calculate theby using exp(-(x*x)).

Sample Input/Output:

(Input is in bold)

Run again(1=yes,0=no)? 1

How many trials? 100

Integral = 0.720000

Run again(1=yes,0=no)? 1

How many trials? 10000

Integral = 0.746400

Run again(1=yes,0=no)? 1

How many trials? 1000000

Integral = 0.746515

Explanation / Answer

Here's a pastebin for syntax highlighting and proper indentation:

http://pastebin.com/N7aJ0qm9

#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;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote