# 蒙地卡羅的題目有人可以為我解答嗎 用c加語言做!!!!

Update:

Rating

#include <conio.h>

#include <math.h>

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

unsigned N;

#define S 16

int dist[S*2*2+1]; // S step * 2unit * 2gridsPerUnit + The longestest

void showDistribution(unsigned n)

{int i, last, max;

for (last=S*2*2; !dist[last]; last--);

last++;

for (max=i=0; i<last; i++)

{ printf("The times the drunker stop at distance [%2d.%c to %2d.%c) is%8d\n",

i>>1, (i&1)?'5':'0', (i+1)>>1, (i&1)?'0':'5', dist[i]);

if (dist[max] < dist[i])

max = i;

}

if (n != N)

printf("I am doing the %dth simulation. %.2f%% complete.\n", n, (double)n*100/N);

else

printf("\nThe result is based on %d Monte Carlo simulation.\n", N);

printf("The most possible distance the drunker stop at will be [%2d.%c to %2d.%c), %.2f%%\n",

max>>1, (max&1)?'5':'0', (max+1)>>1, (max&1)?'0':'5', (double)dist[max]*100/n);

}

int main(int argc, char *argv[])

{ double d, th, x, y;

#ifdef __cplusplus

const

#endif

double pi2 = acos(-1.) * 2;

unsigned i;

int j;

if (argc > 1)

{ _atodbl((_CRT_DOUBLE*) &d, argv[1]); // non-standard

N = (unsigned) d; // or N = atoi(argv[1])

}

if (N < 512)

N = 1024;

srand((unsigned) time(NULL)); rand();

for (i=0; i<N; i++)

{ x = y = 0;

for (j=0; j<S; j++)

{ th = (double) (rand() * pi2) / (RAND_MAX +1);

x += cos(th);

y += sin(th);

} d = sqrt(x*x + y*y) * 2;

// printf("The drunker is at (% 10f, % 10f).\tThe distance is %9f%\n", x, y, d);

dist[(int)(d*2)]++;

if (_kbhit()) // non-standard

{ showDistribution(i);

if ((j=getch()) == 0)

j = getch();

if (j == 27) // press ESC to stop

break;

} }

showDistribution(i);

system("pause");

return 0;

}

在命令列下參數，可改變測的次數。

自訂值為 1024

用了兩個非標函式，使用請小心

2008-12-06 21:01:17 補充：

1024 實在太小了

建議改到10萬以上

2008-12-07 07:03:50 補充：

漏寫一項：C 附的 rand 不適合做蒙地卡羅！

這裡用 rand 寫，只是偷懶！

不過，你這題還好，上述問題不明顯。

欲知原因，或對 rand 有多一點了解，參敝人論壇

http://www.phpbbserver.com/graphicsparalle/viewtop...

Source(s): , 連答三題蒙地卡羅，怎麼沒人請我去蒙地卡羅住／玩？