参数传递的问题

时间:2014-04-09 21:20:50

标签: c

给出以下代码:

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

#define NPOINTS 200
#define NMEASURES 50
#define PI 3.1415f

double mcIntSingleExp1(int);
double mcIntSingleExp1(int n){
  int i, countIn = 0;
  double x,y, integral1, integral2;      
  srand(time(NULL));
  for(i = 0; i < n; i++){
     x = ((double)rand()/(double)RAND_MAX)*PI;
     y = (double)rand()/(double)RAND_MAX;

     if(y <= sin(x))
         countIn++;
  }
  integral1 = (PI * (double)countIn)/(double)n;
  countIn = 0;
  for(i = 0; i < n; i++){
     x = ((double)rand()/(double)RAND_MAX) + PI;
     y = ((double)rand()/(double)RAND_MAX) -1;

     if(y >= sin(x))
         countIn++;
  }
  integral2 = (PI * (double)countIn)/(double)n;
  return integral1 - integral2;
}

double mcIntSingleExp2(int);
double mcIntSingleExp2(int n){
  int i;
  double x, sum = 0;      
  srand(time(NULL));
  for(i = 0; i < n; i++){
     x = ((double)rand()/(double)RAND_MAX) + 2*PI;
     sum += sin(x);
  }
  return (1/(double)n) * sum;
}

void mcIntMultExp1(int, double [], int);
void mcIntMultExp1(int k, double res1[], int n){
  int i;
  for(i = 0; i < k; i++)
      res1[i] = mcIntSingleExp1(n);
}

void mcIntMultExp2(int, double [], int);
void mcIntMultExp2(int k, double res2[], int n){
  int i;
  for(i = 0; i < k; i++)
      res2[i] = mcIntSingleExp2(n);
}

double mean(double [], int);
double mean(double v[], int size){
  int i;
  double sum = 0;
  for(i = 0; i < size; i++)
     sum += v[i];
  return sum/(double)size;
}

double stdDev(double [], int);
double stdDev(double v[], int size){
  int i;
  double avg, std_dev = 0;
  avg = mean(v,NMEASURES);
  for(i = 0; i < size; i++)
     std_dev += (v[i]-avg)*(v[i]-avg);
  return sqrt(std_dev/(double)size);           
}

int main(){
  double measure, deviation, res1[NMEASURES], res2[NMEASURES];
  mcIntMultExp1(NMEASURES, res1, NPOINTS/2);
  mcIntMultExp2(NMEASURES, res2, NPOINTS);
  measure = mean(res1, NMEASURES);
  deviation = stdDev(res1, NMEASURES);
  printf("\nIntegral 1 = %.14lf\nStandard Deviation 1 = %.14lf\n",measure,deviation);
  measure = mean(res2, NMEASURES);
  deviation = stdDev(res2, NMEASURES);
  printf("\nIntegral 2 = %.14lf\nStandard Deviation 2 = %.14lf\n",measure,deviation);
  return 0;
}

在stdDev函数中,我注意到向量v的每个元素都等于avg(v [0] = v [1] = ... = avg),因此标准差为零!实际上,v的元素应该是res1或res2的元素。我不明白有什么不对!

1 个答案:

答案 0 :(得分:5)

您的代码可能运行得足够快,time(NULL)通常会返回相同的值。使用给定种子执行srand后,对rand的以下调用每次都会返回相同的值。

我们通常只在程序开始时执行一次srand(time(NULL))