[英]Why is my program to calculate Mean square error not giving any output?
So I have this question in statistics that I need to solve using C programming.所以我在统计中有这个问题需要使用 C 编程来解决。 We have to calculate the values of MSE for various values of theta(population parameter of exponential distribution) and n(sample size. We set theta as constant and calculate MSE for various values of n, and then make n constant and calculate MSE for various theta.
我们必须为theta(指数分布的总体参数)和n(样本大小)的各种值计算MSE的值。我们将theta设置为常数并为n的各种值计算MSE,然后使n为常数并为各种计算MSE θ。
Then we tabulate the results.然后我们将结果制成表格。
This is my program这是我的程序
# include <stdio.h>
# include <math.h>
# include <stdlib.h>
int main(void)
{
int n ,N=5;
float theta,msum =0.0,mse; //paramters
int i,j; // loop
printf("Enter the value of n ");
scanf("%d", &n);
printf("Enter the value of theta ");
scanf("%f ", &theta);
//float u[n], x[n];
//first we fix theta and find MSE for different values of n
for(i=0;i<N;i++)
{
float sum = 0.0;
for(j=0;j<n;j++)
{
//x[j] = (-1/theta)*log(1-(rand()/RAND_MAX));
sum += (-1/theta)*log(1-(rand()/RAND_MAX)); //generates random number from unifrom dist and then converts it to exponential using inverse cdf function
printf("%d%d", i, j);
}
float thetahat = n/sum;
msum += (thetahat - theta)*(thetahat - theta);
}
mse = msum/N;
printf("The MSE with n=%d and theta=%f is %f", n, theta, mse);
return 0;
}
However, this program is not giving any output.但是,这个程序没有给出任何 output。 I tried multiple IDEs.
我尝试了多个 IDE。 Error count is zero.
错误计数为零。 What am I doing wrong?
我究竟做错了什么?
Use floating point division使用浮点除法
rand()/RAND_MAX
is int
division with a quotient of 0 or 1. Uses 1.0 * rand() / RAND_MAX
to coax a floating point division. rand()/RAND_MAX
是商为 0 或 1 的int
除法。使用1.0 * rand() / RAND_MAX
来哄骗浮点除法。
Avoid log(0)
避免
log(0)
log(1-(rand()/RAND_MAX)
risks log(0)
, even with 1.0 * rand() / RAND_MAX
. I suspect log(1.0 * (RAND_MAX + 1LL - rand()) / (RAND_MAX + 1LL)
will achieve your goal. log(1-(rand()/RAND_MAX)
风险log(0)
,即使使用1.0 * rand() / RAND_MAX
。我怀疑log(1.0 * (RAND_MAX + 1LL - rand()) / (RAND_MAX + 1LL)
会实现你的目标。
Why the space?为什么是空间?
The trailing space obliges scanf()
to not return until non-white-space inputs occurs after the number.尾随空格迫使
scanf()
在数字后出现非空白输入之前不返回。 Drop the space and check the return value.删除空格并检查返回值。
if (scanf("%f", &theta) != 1) {
; // Handle bad input
}
double
vs. float
double
与float
Code curiously uses float
objects, yet double
function calls.代码奇怪地使用了
float
对象,但调用了double
function。
Use double
as the default floating point type in C unless you have a compelling need for float
.在 C 中使用
double
作为默认浮点类型,除非您对float
有迫切的需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.