Anweshan Goswami
Anweshan Goswami

Reputation: 1

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. 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.

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. I tried multiple IDEs. Error count is zero. What am I doing wrong?

Upvotes: 0

Views: 82

Answers (1)

chux
chux

Reputation: 153458

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.

Avoid 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.

Why the space?

The trailing space in scanf("%f ", &theta) obliges scanf() to not return until non-white-space inputs occurs after the number. Drop the space and check the return value.

if (scanf("%f", &theta) != 1) {
  ; // Handle bad input
}

double vs. float

Code curiously uses float objects, yet double function calls.

Use double as the default floating point type in C unless you have a compelling need for float.

Upvotes: 0

Related Questions