I have tried many different approaches and it keeps giving me errors...I am definitely not the best coder, please help! I have tried to create a histogram in many different ways, I know the logic behind making a histogram but I do not know how to implement that into C. I need to create a histogram for the x array.
The problem: Write a computer routine to generate 2,000 values from the given cdf F(x)=x^4/16 on 0<=x<=2. Make a histogram of the 2,000 values and compare it to the theoretical cdf.
int main()
{
int i, b, d, e, j, bins=9, n=2000, y[2000], hist[9];
double seed = 12;
double temp=0, r[2000], temp2=0, x[2000];
int a = 1093, c = 18257, m = 86436;
printf("\nThis program will calculate random variates based on the given CDF\n :x^4/16 on 0<=x<=2\n ");
y[0]=seed;
for (i=1; i<n; i=i+1){
y[i] = (a*y[i-1] + c) % m;
temp = y[i];
r[i] = temp / m;
temp2 = r[i];
x[i] = pow(16*temp2,0.25);
printf("%d %.4lf %lf\n", y[i], r[i], x[i]);
}
//all of my attempts below
/*
int *buildHist(int bins, double min, double max, int n, double *data){
double *hist=malloc(bins*sizeof(int));
if (hist == NULL) return hist;
for (int i=0; i<n; ++i){
int bin=int( (data[i]-min)/((max-min)/(bins)) );
if ( (bin>=0) && (bin<n) ) hist[bin]++;
}
return hist;
}
int max = x[0];
for (d = 1; d < n; d=d+1){
if (x[d] > max)
max = x[d];
}
printf("The max is : %lf\n", max);
int min = x[0];
for (b =1; b<n; b=b+1){
if (x[b] < min)
min = x[b];
}
printf("The min is : %lf\n", min);
//Dividing data into bins
for (b = 0; b < n; b+1){
for (j = 1; j <= bins; j+1){
float bin_max = (float)j / (float)bins;
if (x[b] <= bin_max){
hist[j]+1;
break;
}
}
}
// Plotting histogram
printf("\n\nHistogram of Float data\n");
for (d = 1; d <= bins; d+1){
count = hist[d];
printf("0.%d |", d - 1);
for (e = 0; e < count; e+1)
{
printf("%c", (char)254u);
}
printf("\n");
}
*/
return 0;
}
I guess that your problem is that malloc()
returns non-initialized memory. This means that your hist
already contains garbage values which you then increment with hist[bin]++
.
Use calloc()
to allocate hist
or use the memset()
C library function to clear hist
before use.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.