English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I don't think anyone will acutally write the program (if you do, please use C language).

Looking for psuedocode on how to go about it.

2007-04-25 01:14:09 · 2 answers · asked by Russel Teek 1 in Computers & Internet Programming & Design

2 answers

(1) Pick N random values between 0 and pi/2
(2) 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/2) times the average value over your chosen data.

Here it is in Java, which is similar enough to 'C' that you should be able to translate:

public static void main(String[] args) {
final int NUM_SAMPLES = 10000;
double sum = 0.0;
for (int i=0; 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 = 1.0034539704012315

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

If you also have to estimate the error in the result, that is noticeably more complex (see the second source below).

2007-04-25 01:34:52 · answer #1 · answered by McFate 7 · 0 0

let u = cos^2(x) du = -2sinxcosx dx = -sin(2x) dx -INT(u)du = -u^2/2 + C = -cos^4(x)/2 + C | x = 0 and pi/2 = 1/2

2016-05-18 02:31:03 · answer #2 · answered by ? 3 · 0 0

fedest.com, questions and answers