Hiya我试图为基本的1D Monte-Carlo集成编写代码。为此,我需要一个伪随机数列表,然后我可以将其输入到一个函数中(存储在另一个子例程中)。我已经给出了随机数列表指针,但是当我尝试在main中取消引用时,我得到“错误:从类型'double'”分配类型'double [11]'时不兼容的类型。谁能告诉我哪里出错了?我的代码可以在这里找到:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#ifndef RAND_MAX
#define RAND_MAX 2147483648
#endif
#define N 10
double function(double x);
double* rdm(void);
void main(void)
{
double* Random_number_list;
int i;
double sum = 0.0, sum2 = 0.0, X[N+1],S, Random_number_list2[N + 1];
double F[N+1], lower, upper, avg, avg2;
printf("Lower Bound: ");
scanf("%lf", &lower);
printf("Upper Bound: ");
scanf("%lf", &upper);
Random_number_list2 = *Random_number_list;
for (i = 0; i <= N; i++) {
X[i] = ((upper - lower)*Random_number_list2[i]) + lower;
F[i] = function(X[i]);
sum = sum + F[i];
sum2 = sum2 + (F[i] * F[i]);
}
avg = sum / N;
avg2 = sum2 / N;
S = (upper - lower) * (avg + sqrt((avg2 - (avg * avg)) / N));
printf("The Monte Carlo approximation is %lf\n", S);
}
double function(double x)
{
double y;
y = sin (x);
return y;
}
double* rdm(void)
{
double* Random_number_list = calloc(N + 1, sizeof(double));
int i;
srand(time(NULL));
for (i = 1; i <= N; i++) {
Random_number_list[i] = (float) rand() / (float) RAND_MAX;
}
return Random_number_list;
}
非常感谢。杰克梅德利
答案 0 :(得分:4)
假设:
int * a;
int b[5];
然后你可以写:
a = b; // copying a pointer, same as a = &b[0];
但是,你不能写:
b = a; // b's memory is allocated, you cannot swap it out.
这意味着,丢失Random_number_list2
,只使用Random_number_list
。
你想:
double* Random_number_list = rdm();
以后
// added space, so it's clearer you're multiplying and not dereferencing.
X[i] = ((upper - lower) * Random_number_list[i]) + lower;