https://blog.csdn.net/yillc/article/details/6740425
基本思想:所求解的問題是某隨機事件A出現的概率,通過某種實驗方法,得出A的頻率,以此估計A事件出現的概率。
蒙特卡洛求面積:隨機在矩形裏面產生大量的隨機點(數量爲N),計算有多少點(數量爲c)落在區域面積內,S是矩形的面積,那麼S*(c/N)就是所求區域的面積。
1.求曲線圍成的面積:
clc
clear
close all
P=rand(10000,2);
x=2*P(:,1)-1;
y=2*P(:,2);
II=find(y<=2-x.^2&y.^3>=x.^2);
M=length(II);
S=4*M/10000
plot(x(II),y(II),'g.')
2.求國土面積
clc
close all
clear
x =[7.0 10.5 13.0 17.5 34.0 40.5 44.5 48.0 56.0 61.0 68.5 76.5 80.5 91.0 96 101 104 106.5 111.5 118 123.5 136.5 142 146 150 157 158 ];
y1= [44 45 47 50 50 38 30 30 34 36 34 41 45 46 43 37 33 28 32 65 55 54 52 50 66 66 68];
y2= [44 59 70 72 93 100 110 110 110 117 118 116 118 118 121 124 121 121 121 122 116 83 81 82 86 85 68];
long=max(x)-min(x);
height=max(y2)-min(y1);
are=[];
for k=1:10
s=0;
for i=1:1000
ranx(i)=unifrnd(min(x),max(x));
rany(i)=unifrnd(min(y1),max(y2));
newy1=interp1(x,y1,ranx(i),'spline');
newy2=interp1(x,y2,ranx(i),'spline');
if(rany(i)>=newy1&rany(i)<=newy2) s=s+1;
end
end
are=[are long*height*s/10000/18^2*1600]
end
mean(are)
每一輪循環中先用unifrnd函數生成一個點(在最大範圍的矩陣中),再用interp1函數插值計算在生成點x處的函數值,判斷是否在國土面積內,若是,s=s+1.
for循環做了十次面積求解,每次的答案存放在are()數組中,最後取均值。