show all threads
[tridge/junkcode.git] / sort_density.c
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 #define N_PER_BIN 20000
5 #define BINS 10
6 #define HBINS 20
7
8 float bins[BINS][N_PER_BIN];
9
10 float frandom(float low,float high)
11 {
12   unsigned long r = random();
13   r = r % (2<<20);
14   return low + (high - low)*((double)r)/(2<<20);
15 }
16
17 void create_bin(float *bin)
18 {
19   int i;
20   for (i=0;i<N_PER_BIN;i++) bin[i] = frandom(0.0,1.0);
21 }
22
23 void create_bins(void)
24 {
25   int i;
26   for (i=0;i<BINS;i++)
27     create_bin(bins[i]);
28 }
29
30
31 int cmp(float *f1,float *f2)
32 {
33   if (*f1 > *f2) return 1;
34   if (*f1 < *f2) return -1;
35   return 0;
36 }
37
38 void merge(float *bin1,float *bin2)
39 {
40   float combined[N_PER_BIN*2];
41
42   memcpy(combined,bin1,sizeof(bin1[0])*N_PER_BIN);
43   memcpy(combined+N_PER_BIN,bin2,sizeof(bin1[0])*N_PER_BIN);
44   qsort(combined,2*N_PER_BIN,sizeof(combined[0]),cmp);
45
46   memcpy(bin1,combined,sizeof(bin1[0])*N_PER_BIN);
47   memcpy(bin2,combined+N_PER_BIN,sizeof(bin1[0])*N_PER_BIN);
48   
49 }
50
51
52 show_density(float *bin,char *name)
53 {
54   float hist[HBINS];
55   int i;
56   FILE *f;
57
58   for (i=0;i<HBINS;i++) hist[i] = 0;
59
60   for (i=0;i<N_PER_BIN;i++) {
61     int j = (int)((bin[i]-0.0001) / 0.05);
62     hist[j]++;
63   }
64   for (i=0;i<HBINS;i++) {
65     hist[i] = (hist[i]*HBINS)/(float)N_PER_BIN;
66   }
67
68   f = fopen("hist.dat","w");
69   for (i=0;i<HBINS;i++) 
70     fprintf(f,"%f\n",hist[i]);
71   fclose(f);
72
73   f = popen("gnuplot","w");
74   if (!f) {
75     printf("failed to launch gnuplot\n"); 
76     return;
77   }
78   fprintf(f,"
79 set yrange [0:2]
80 set data style linespoints
81 plot \"hist.dat\"
82 ");
83
84   fflush(f);
85   getchar();
86   fclose(f);
87 }
88
89
90 main(void)
91 {
92   create_bins();
93
94   merge(bins[0],bins[1]);
95
96   show_density(bins[0],"none");
97   show_density(bins[1],"none");
98 }