How would you calculate the integral of sinx from 0 to pi us

How would you calculate the integral of sin(x) from 0 to pi using Monte Carlo integration?

Solution

(1) First, let us pick N random values between 0 and pi
(2) Then need to compute the average value of sin(x) for the chosen points (sum up sin(x) for every one of your data points and divide by the number of points)
(3) The approximation is the width of the range (pi) times the average value over your chosen data.

The code is written in Java here, which is similar enough to \'C\' that you will be able to translate:

public static void main(String[] args) {
final int NUM_SAMPLES = 10000;
double sum = 0.0;
for (int i=0; i<NUM_SAMPLES; ++i)
sum += Math.sin(Math.random() * Math.PI / 2.0);
System.out.println(\"Samples = \" + NUM_SAMPLES +
\"; Monte Carlo Integration = \" +
((Math.PI / 2.0) * (sum / NUM_SAMPLES)));
}

When this program is executed, the result is:

Samples = 10000; Monte Carlo Integration = 2.0034539704012315

... which is approximately correct. Integral from 0 to pi of sin(x)dx = 2.

How would you calculate the integral of sin(x) from 0 to pi using Monte Carlo integration?Solution(1) First, let us pick N random values between 0 and pi (2) Th

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site