Assignment 3

The purpose of this assignment is to learn about the basics of simulation and sorting.

  1. Write a function double rand_unif() that generates a U(0, 1) pseudo-random number using the random() function.

  2. Write a function void dswap(double *x, double *y) that swaps the values stored in the locations x and y. Here, x and y are to be interpreted as pointers to scalars, not arrays. For example, the code snippet

    double x = 0, y = 1;
    dswap(&x, &y);
    should result in x having value 1 and y having value 0.

  3. Write a function void dsort(double *x, int n, int *ncomp, int *nswap) that takes an array x as input and changes it "in-place" to its sorted version. The function should also compute the number of comparisons made and the number of swaps done, and record these in the locations pointed to by ncomp and nswap. This is a common trick used in C programming to "return" more than one value.

    Implement whatever sorting algorithm you can think of yourself, rather than trying to find an efficient one. We will discuss various sorting algorithms in class later.

  4. Write a function double *rbeta(int m, int n, int dsize) that uses rand_unif() and dsort() to simulate an array (of length dsize) of Beta(m, n) random variates.

  5. Using the lgamma function in math.h and relevant parts from assignment 2, write a function void beta_mle(double *x, int *m, int *n, int k) that computes the MLE of (m, n) for integer m and n where 1 \leq m, n \leq k, and stores the resulting estimates in *m and *n.

  6. Write a function void sim_beta_mle(int m, int n, int dsize, int k) that simulates dsize Beta(m, n) random variates, computes the MLE for integer 1 \leq m, n \leq k, and prints the MLEs of m and n (in a single line).

  7. Write a main function that uses command-line arguments to obtain integers m, n, dsize, and nrep (in that order) from the user, computes k = 2 * max(m, n), and then calls sim_beta_mle(m, n, dsize, k) nrep times (thus producing a printout of the MLEs, one replication per line).

Submit your program by email by midnight of Monday February 13.


Last updated: Thu Mar 8 2012