0

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?

  • 2
    Integer division: `rand() / RAND_MAX` is usually `0` and rarely `1`. I suggest `(float)rand() / RAND_MAX`. Aside: generally you should use `double` unless you have a definite reason why you need to use the inferior `float`. – Weather Vane Sep 02 '22 at 19:24
  • 1
    `scanf("%f ", &theta);` see that trailing space? Please see [What is the effect of trailing white space in a scanf() format string?](https://stackoverflow.com/questions/19499060/what-is-the-effect-of-trailing-white-space-in-a-scanf-format-string) – Weather Vane Sep 02 '22 at 19:35
  • Another aside: please put a newline `\n` at the end of every `printf` formatting string, to avoid garbled nonsense being output. – Weather Vane Sep 02 '22 at 19:36

1 Answers1

0

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.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256