Advertisement
Guest User

Basic Monte Carlo Approximation

a guest
Aug 31st, 2015
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.60 KB | None | 0 0
  1. function Value = Approx_Integral(F, x_Min, x_Max)
  2.     Approximation = [];
  3.     if(x_Min <= x_Max)
  4.         %f_Min = fminbnd(F,x_Min,x_Max) this wasn't returning the right
  5.         %values and I'm not sure why
  6.         x=x_Min:.00001:x_Max;
  7.         f_Min = min(F(x));
  8.         f_Max = max(F(x));
  9.         for k = 1:10 %creates ten seperate approximations and will eventually take the mean of all of them
  10.             Random_Pointsx = rand(1,ceil((x_Max-x_Min)*10000))*(x_Max-x_Min)+x_Min;
  11.             Random_Pointsy = rand(1,ceil((x_Max-x_Min)*10000))*(f_Max-f_Min)+f_Min;
  12.             Random_Points = [Random_Pointsx; Random_Pointsy];%generates the random
  13.                      %points within the box containing the section of the function
  14.             hits = 0;
  15.             for i = 1:(x_Max-x_Min)*10000
  16.                 if(Random_Points(2,i)< 0)
  17.                     if(Random_Points(2,i) >= F(Random_Points(1,i)))
  18.                     hits = hits -1;%area below y=0 is subtracted
  19.                     end
  20.                 else if (Random_Points(2,i) <= F(Random_Points(1,i)))
  21.                     hits = hits + 1;%area above y=0 is added
  22.                     end
  23.                 end
  24.             end
  25.             Approximation = [Approximation, hits/(x_Max*10000)*(x_Max-x_Min)*(f_Max-f_Min)];
  26.             %adds current iteration's approximation to the list of k
  27.             %approximations
  28.         end
  29.         Value = mean(Approximation);%takes the mean of  the k approximations
  30.     else
  31.         Value = -1*Approx_Integral(@(x)F(x), x_Max, x_Min);
  32.         %since b<a, switches bounds and multiplies by -1
  33.     end
  34. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement