next up previous
Next: What to turn in Up: Part Two Previous: Random doubles

Check the random number generator

If the random number generator is doing what it says it does, then we should be able to check it. For example, if we generate many random numbers, their average should be near 0.5. Furthermore, the standard deviation should be near 0.25.

1.
Write a method named avgArray that takes as arguments an array of doubles and the (integral) length of the array. It should return a double that is the average of the values in the array.
2.
Test your program by invoking it from main. Try it out on bigger arrays, like 100, 1000 and 10000 elements. You will want to comment out the invocation of printArray before you get to the really big arrays.

As the array size gets bigger, does the average value converge on 0.5?

3.
Write a method named stdArray that takes the same arguments as avgArray, and returns the standard deviation of the values in the array. The standard deviation is defined as:

\begin{displaymath}
std = \sqrt{\frac{\sum_{i=0}^{n-1} (x_i - \mu)^2}{n}} \end{displaymath}

where n is the number of elements, xi is the ith element of the array, and $\mu$ is the average, as calculated by avgArray.

HINT: Since you need to know the average to calculate the standard deviation, you might want stdArray to invoke avgArray. Or, you might change the interface to stdArray so that it takes the average as a third argument.

As the size of the array increases, does the standard deviation converge on 0.25 as expected? Which takes longer to converge, the mean or the standard deviation? In other words, how big does the array have to be for the mean to be within 0.01 of 0.5? How big does the array have to be for the standard deviation to be withing 0.01 of 0.25?


next up previous
Next: What to turn in Up: Part Two Previous: Random doubles
Allen B. Downey
3/18/1998