Answer:
/ TestRandom.java
import java.util.Random;
public class TestRandom {
// method to find the mean value of set of numbers
// using Number as data type, so that it can represent both Double and Long
// types needed for this program
static double calculateMean(Number array[]) {
double sum = 0;
// summing values
for (int i = 0; i < array.length; i++) {
sum += array[i].doubleValue();
}
// finding average and returning it
double avg = (double) sum / array.length;
return avg;
}
// method to find the standard deviation value of set of numbers
// using Number as data type, so that it can represent both Double and Long
// types needed for this program
static double calculateSD(Number array[], double mean) {
// initializing sum of squared difference between each number and mean
// to 0
double sumSquaredDiff = 0;
// looping
for (int i = 0; i < array.length; i++) {
// finding difference between current number and mean, squaring the
// result, adding to sumSquaredDiff
sumSquaredDiff += Math.pow(array[i].doubleValue() - mean, 2);
}
// finding variance
double variance = (double) sumSquaredDiff / array.length;
// finding square root of variance as standard deviation
double sd = Math.sqrt(variance);
return sd;
}
public static void main(String[] args) {
// if no command line arguments given, displaying usage and quit
if (args.length == 0) {
System.out.println("Usage: java TestRandom <n>");
System.exit(0);
}
// parsing first argument as integer N
int N = Integer.parseInt(args[0]);
// declaring a Double array and a Long array of size N
Double gaussian[] = new Double[N];
Long lng[] = new Long[N];
// Random number generator
Random random = new Random();
// looping for N times
for (int i = 0; i < N; i++) {
// generating a guassian number, adding to array
gaussian[i] = random.nextGaussian();
// generating a long number, adding to array
lng[i] = random.nextLong();
}
// finding average and standard deviation of both array values, we can
// use the same functions for both types
double avgGaussian = calculateMean(gaussian);
double sdGaussian = calculateSD(gaussian, avgGaussian);
double avgLong = calculateMean(lng);
double sdLong = calculateSD(lng, avgLong);
// displaying mean and standard deviation of both, formatted to 2 digits
// after decimal point. the gaussian values will yeild a mean value
// close to 0 and a standard deviation close to 1
System.out.printf("Mean of %d gaussian values: %.2f\n", N, avgGaussian);
System.out.printf("Standard deviation: %.2f\n", sdGaussian);
System.out.printf("Mean of %d long values: %.2f\n", N, avgLong);
System.out.printf("Standard deviation: %.2f\n", sdLong);
}
}
Explanation: