一道C++或者matlab模拟 Monte-Carlo的题

来源:百度知道 编辑:UC知道 时间:2024/06/04 14:41:45
3.H Monte-Carlo simulation. Make a C++ (or Matlab) program to compute the area under the function f(x) = sin(x) in the range [0,1] using Monte-Carlo simulation. How accurate is the result with K=1, 10, 100, 1000, 10000, 100000, 1000000 iterations? Precise value = 1-cos(1)

还是不太清楚怎么用Monte-Carlo simulation
谢谢啦,呵呵。

#include<stdio.h>
#include<math.h>

void main()
{
double x,y,v;
double sum1,sum2,area;
double r;
long int k[] ={ 1, 10, 100, 1000, 10000, 100000, 1000000};
long int i,j;

r = 1.0 - cos(1.0);
printf("r=%lf\n",r);

for (j=0;j<7;j++)
{
sum1=0.0;
sum2=0.0;
srand((unsigned)time(NULL));
for (i=0;i<k[j];i++) {
x= (double) (rand() % 100+1) / 100.0;
y= (double) (rand() % 100+1) / 100.0;
v = sin(x);
if ( y <= v) {sum1=sum1+1;} else {sum2=sum2+1;};
}
area = sum1 / (sum1 + sum2);
printf("%d %lf %lf\n",k[j],area,area/r);
};
}

k[j] -- 次数
area -- 面积
area/r -- 精度

汗~~这个是大学里面<计算方法>里面的内容,关于蒙特卡洛算法的,这个不可能在这里讲清楚。不过如果你真想知道,就找本《计算方法》的教材详细研究一下。不过提前声明,对于非计算机专业出身或者数学出身的人来说,可能自学有些难度。

...就是随机撒点,然后统计概率,没了...

比如说,随机撒1000000次点,看有多少个点满足y <= sin(x),那么面积就是n / 1000000,非常简单