zoukankan      html  css  js  c++  java
  • 水库采样算法


    //水库采样 用较小的开销来估计一个较大的数据流
    1
    #include<stdio.h> 2 #include<stdlib.h> 3 #include<time.h> 4 int main() 5 { 6 int count=0; 7 long long int sum_all=0; 8 long int sum=0; 9 int i=0; 10 int data;//取数据 11 int length=500;//水库大小 12 int *set=(int *)malloc(length*sizeof(int));//定义一个集合 13 int index=0;//下标 14 int randIndex=0;//随机下标 15 double randNum=0;//随机数 16 FILE *fp=fopen("stream_sample.txt","r"); 17 srand(time(0));//以time(0)为种子 18 if(!fp) 19 { 20 printf("file open failed ! "); 21 system("pasue"); 22 return -1; 23 } 24 while(!feof(fp)) 25 { 26 fscanf(fp,"%d",&data);//取文本中的数据 27 sum_all+=data;//所有数据之和 28 //打印所有数据 29 //printf("%d ",data); 30 if(index<length)//水库填充时 31 { 32 set[index]=data; 33 index++; 34 } 35 else//水库被填充满时 36 { 37 randNum=(rand()%(index+1)); 38 if(randNum<length) 39 { 40 randIndex=rand()%length; 41 set[randIndex]=data; 42 } 43 index++; 44 } 45 46 } 47 printf(" ----------------------------------------- "); 48 printf("一共有%d个数据 ",index); 49 printf(" ----------------------------------------- "); 50 printf("水库中的数"); 51 for(i=0;i<length;i++) 52 { 53 printf("%d ",set[i]); 54 } 55 printf(" "); 56 57 printf(" ----------------------------------------- "); 58 59 printf(" ----------------------------------------- "); 60 for(i=0;i<length;i++) 61 { 62 sum+=set[i];//水库中的叠加 63 } 64 printf("%lf %lf",(double)sum/length,(double)sum_all/(index-1)); 65 printf(" "); 66 67 fclose(fp); 68 system("pause"); 69 return 0; 70 }

    只是简单理解,代码还有许多不足之处

  • 相关阅读:
    Python自动化开发-基础语法
    Python自动化开发-简介
    Hello World!
    Mongo导出数据文件导致错误 Got signal: 6 (Aborted)解决方法
    PHP快速排序及其时间复杂度
    PHP读某一个目录下所有文件和文件夹
    PHP获得两个绝对路径的相对路径
    awk神器
    PHP使用Mysql事务
    PHP使用session_set_save_handler陷阱
  • 原文地址:https://www.cnblogs.com/SimonKly/p/6838805.html
Copyright © 2011-2022 走看看