计算均值的奇怪问题

时间:2015-04-11 19:38:02

标签: c

我正在尝试计算monte carlo模拟的数组的平均值,但由于某种原因它给了我一个庞大的数字,我不能为我的生活找出导致它的原因。

这是代码

void montecarlo()
{
    int arraysize,*ptr, stat=1;
    float randx, avg, stdev,summ=0;

while (stat==1)
    {
        printf("Please Enter the number of simulations to run, between 1,000 and 10,000 without a comma\n");
        scanf("%d",&arraysize);
        if (arraysize<1000 || arraysize>10000)
        {

            printf("Improper array size! \n");
            stat=1;
        }
        else
        {
            stat=0;
        }
    }
        ptr=(int*)calloc(arraysize, sizeof(int));

        for (i=0; i<arraysize; i++)
        {
            random_dimension(2.00, 0.50, &randx );
            printf("%f\n",randx);
            ptr[i]= randx;
            summ+= ptr[i];

        }
        avg=summ/arraysize;
        printf("%f\n",avg);
    srand(time(NULL));
    free(ptr);
}

这是输出,首先打印随机生成的值,然后打印平均值(质量值)。 我无法发布图片,但它会在2附近打印十进制值。计算的平均值是 9414187188170815000000000000.000000     这是random_dimension函数:

void random_dimension(float nom, float tol, float *random_value)
{

    float r1, r2, r12;
    float sigma = tol / 3;
    do{
    r1 = (float)( rand() % 10001 ) / 10000;
    }while (r1==0);
    r2 = (float)( rand() % 10001 ) / 10000;
    r12 = sqrt(-2*log(r1))*cos(2*M_PI*r2);
    *random_value = nom + sigma * r12;


}

1 个答案:

答案 0 :(得分:0)

我修好了。我需要做的是将动态数组更改为浮动类型。 固定代码:

int arraysize, stat=1;
    float randx, avg, stdev, *ptr ,summ=0;

    while (stat==1)
    {
        printf("Please Enter the number of simulations to run, between 1,000 and 10,000 without a comma\n");
        scanf("%d",&arraysize);
        if (arraysize<1000 || arraysize>10000)
        {

            printf("Improper array size! \n");
            stat=1;
        }
        else
        {
            stat=0;
        }
    }
        ptr=(float*)calloc(arraysize, sizeof(float));

        srand(time(NULL));
        for (i=0; i<arraysize; i++)
        {
            random_dimension(2.00, 0.50, &randx );
            ptr[i]= randx;
            summ+= ptr[i];
            printf("%f\n",ptr[i]);

        }
        avg=summ/arraysize;
        printf("\n\n%f\n",avg);


    free(ptr);
}