1

I am trying to figure out how to right a math based app with Matlab, although I cannot seem to figure out how to get the Monte Carlo method of integration to work. I feel that I do not have algorithm thought out correctly either. As of now, I have something like:

    // For the function {integral of cos(x^3)*exp(x^(1/2))+x dx
    // from x = 0 to x = 10
    ans = 0;
    for i = 1:100000000
        x = 10*rand;
        ans = ans + cos(x^3)*exp(x^(1/2))+x
    end

I feel that this is completely wrong because my outputs are hardly even close to what is expected. How should I correctly write this? Or, how should the algorithm for setting this up look?

2

2 Answers 2

5

Two issues:

1) If you look at what you're calculating, "ans" is going to grow as i increases. By putting a huge number of samples, you're just increasing your output value. How could you normalize this value so that it stays relatively the same, regardless of number of samples?

2) Think about what you're trying to calculate here. Your current "ans" is giving you the sum of 100000000 independent random measurements of the output to your function. What does this number represent if you divide by the number of samples you've taken? How could you combine that knowledge with the range of integration in order to get the expected area under the curve?

3

I managed to solve this with the formula I found here. I ended up using:

   ans = 0;
   n = 0;
   for i:1:100000000
       x = 10*rand;
       n = n + cos(x^3)*exp(x^(1/2))+x;
   end
   ans = ((10-0)/100000000)*n