【发布时间】:2021-02-19 14:20:20
【问题描述】:
我尝试了许多不同的方法,但它一直给我错误...我绝对不是最好的编码器,请帮助!我尝试以多种不同的方式创建直方图,我知道制作直方图背后的逻辑,但我不知道如何在 C 中实现它。我需要为 x 数组创建直方图。
问题: 编写一个计算机例程,从给定的 cdf F(x)=x^4/16 on 0
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;
}
【问题讨论】:
-
“不起作用”不是问题描述。而且您甚至还没有描述任务的确切要求(仅“创建直方图”还不够具体)。请给出任务描述、预期行为、程序的实际行为以及您有什么具体问题。
-
显示的代码没有显示任何制作直方图的尝试。 “我尝试了许多不同的方法,但没有任何效果。”,所以请展示你拥有的最好的方法,并用minimal reproducible example 证明它是如何失败的。如果我错了并且显示的代码是您的尝试,那么请添加一些 cmets 来解释您的想法。使用比单个字母更长的名称可能会有所帮助。
-
@kaylum 这是一个更好的问题吗?这是我得到的唯一指导。
-
@Yunnosch 我已经更新了我的尝试。我不确定他们为什么会失败,这就是我来这里寻求帮助的原因。我知道您需要找到最大值和最小值来生成 bin,但我真的不知道如何绘制图表。