Guest User

Untitled

a guest
Apr 30th, 2013
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 0.68 KB | None | 0 0
  1. function val = MonteCarlo(fun,a,b,n,hObject)
  2.  
  3. handles=guidata(hObject);
  4. t=[a:0.01:b];
  5. f=fun(t);
  6. axes(handles.montecarlo);
  7. plot(t,f,'LineWidth',2);
  8. title('Monte Carlo');
  9. axis tight;
  10. maxV=max(f);
  11. minV=min(f);
  12.  
  13. k=0;
  14. j=0;
  15. hold on;
  16. for i=1:n
  17.     x=a+(b-a)*rand(1);
  18.     y=minV+(maxV-minV)*rand(1);
  19.    
  20.     if(y>=0 & y<=fun(x)) k=k+1; plot(x,y,'Color','g','LineWidth',2);
  21.     elseif(y<0 & y>fun(x)) j=j+1; plot(x,y,'Color','g','LineWidth',2);    
  22.     else plot(x,y,'Color','r','LineWidth',2);
  23.     end
  24.     val=(k-j)/i*(maxV-minV)*(b-a);
  25.     set(handles.MCval,'String',num2str(val,'%.4f'))
  26.    
  27.    
  28.     pause(0.0001);
  29. end
  30. hold off;
  31. val=(k-j)/n*(maxV-minV)*(b-a);
  32. end
Advertisement
Add Comment
Please, Sign In to add comment