任意离散型随机数发生器

// 任意离散型随机数发生器,程序中输入分布

#include "math.h"
#include "dos.h"
#include "stdio.h"
#define maxnum 800
main()
{
  int i=1,j,n,num;
  int value[20],newrd[800];
  float prob[20];
  long M,a,x0,c,x;
  float radoms[800];
  FILE *fp;

  printf("nDispersed radom numbers generate…");
  printf("nPlease input the num of dispersed values:");
  scanf("%d",&n);
  printf("Input the values:(such as 1 2 3 …—must be integer)n");
  for(i=1;i<=n-1;i++)
    scanf("%d ",&value[i]);
  scanf("%d",&value[n]);
  printf("Input the probablity:n");
  for(i=1;i<=n-1;i++)
    scanf("%f ",&prob[i]);
  scanf("%f",&prob[n]);
  printf("The number of wanted radoms:(maxnum<800)");
  scanf("%d",&num);
  M=pow(2,16);
  a=8*(int)(M/64*3.1415926)+5;
  c=2*(int)(M/2*0.211324845)+1;
  x0=init();
  x=(a*x0+c)%M;
  for(i=0;i<num;i++)
  {
    x=(a*x+c)%M;
    radoms[i]=(float)x/M;
  }
  for(i=2;i<=n;i++)
    prob[i]+=prob[i-1];
  for(i=0;i<num;i++)
  {
   j=1;
   while(radoms[i]>=prob[j]) j++;
   newrd[i]=value[j];
  }
  if((fp=fopen("d:\radoms2.txt","w+"))==NULL)
     printf("nCannot create the file");
  else
  {
    for(i=0;i<num;i++)
    {
      fprintf(fp,"%d ",newrd[i]);
      if((i+1)%10==0) fputc(‘n’,fp);
    }
  }
  fclose(fp);
  printf("OK!nThe program end. The results is at d:\radoms2.txt");
}
init()
{
  struct time t;

  gettime(&t);
  return((int)t.ti_hund);
}

此条目发表在数学分类目录。将固定链接加入收藏夹。

留下评论