Hiya,我的代碼目前有三個函數,每個函數都產生一個大量的隨機數。我想知道是否有隻是有一個函數返回一個鏈表或多維數組使它有點整潔的辦法:有沒有使用鏈表來簡化我的蒙特卡洛代碼
(從http://pastebin.com/Y5aE6XKS複製)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#ifndef RAND_MAX
#define RAND_MAX 2147483648
#endif
#define N 420000
double* rdm_X(void);
double* rdm_Y(void);
double* rdm_Z(void);
void main(void)
{
double* Random_number_list_X = rdm_X();
double* Random_number_list_Y = rdm_Y();
double* Random_number_list_Z = rdm_Z();
double X[N+1], Y[N+1], Z[N+1], density = 1, vol = 42.0;
double sum = 0, sum_x = 0, sum_y = 0, sum_z = 0;
int i;
for (i = 0; i <= N; i++) {
X[i] = 3 * Random_number_list_X[i] + 1;
Y[i] = 7 * Random_number_list_Y[i] - 3;
Z[i] = 2 * Random_number_list_Z[i] - 1;
if ((Z[i]*Z[i]) + (sqrt(X[i]*X[i] + Y[i]*Y[i]) - 3)*(sqrt(X[i]*X[i] + Y[i]*Y[i]) - 3) <= 1) {
sum += density;
sum_x += X[i] * density;
sum_y += Y[i] * density;
sum_z += Z[i] * density;
}
}
printf("(%.5lf, %.5lf, %.5lf)\n",
sum_x/sum, sum_y/sum, sum_z/sum);
}
double* rdm_X(void)
{
double* Random_number_list_X = calloc(N + 1, sizeof(double));
int i;
srand(time(NULL));
for (i = 1; i <= N; i++) {
Random_number_list_X[i] = (float) rand()/(float) RAND_MAX;
}
return Random_number_list_X;
}
double* rdm_Y(void)
{
double* Random_number_list_Y = calloc(N + 1, sizeof(double));
int i;
sleep(1);
srand(time(NULL));
for (i = 1; i <= N; i++) {
Random_number_list_Y[i] = (float) rand()/(float) RAND_MAX;
}
return Random_number_list_Y;
}
double* rdm_Z(void)
{
double* Random_number_list_Z = calloc(N + 1, sizeof(double));
int i;
sleep(2);
srand(time(NULL));
for (i = 1; i <= N; i++) {
Random_number_list_Z[i] = (float) rand()/(float) RAND_MAX;
}
return Random_number_list_Z;
}
你問了六個問題,從未接受答案。試着去做點什麼! – 2010-09-10 20:02:45
爲什麼你的代碼是在pastebin而不是在這裏的任何原因? – pmg 2010-09-10 20:08:33
我沒有意識到我不得不,我現在去做,歡呼 – JMzance 2010-09-11 18:53:07