problem with Random.nextGaussian()

前端 未结 6 2077
别跟我提以往
别跟我提以往 2021-01-12 19:58

Random.nextGaussian() is supposed to give random no.s with mean 0 and std deviation 1. Many no.s it generated are outside range of [-1,+1]. how can i set so that it gives n

6条回答
  •  梦毁少年i
    2021-01-12 20:17

    This code will display count number of random Gaussian numbers to console (10 in a line) and shows you some statistics (lowest, highest and average) afterwards.

    If you try it with small count number, random numbers will be probably in range [-1.0 ... +1.0] and average can be in range [-0.1 ... +0.1]. However, if count is above 10.000, random numbers will fall probably in range [-4.0 ... +4.0] (more improbable numbers can appear on both ends), although average can be in range [-0.001 ... +0.001] (way closer to 0).

    public static void main(String[] args) {
        int count = 20_000; // Generated random numbers
        double lowest = 0;  // For statistics
        double highest = 0;
        double average = 0;
        Random random = new Random();
    
        for (int i = 0; i < count; ++i) {
            double gaussian = random.nextGaussian();
            average += gaussian;
            lowest = Math.min(gaussian, lowest);
            highest = Math.max(gaussian, highest);
            if (i%10 == 0) { // New line
                System.out.println();
            }
            System.out.printf("%10.4f", gaussian);
        }
        // Display statistics
        System.out.println("\n\nNumber of generated random values following Gaussian distribution: " + count);
        System.out.printf("\nLowest value:  %10.4f\nHighest value: %10.4f\nAverage:       %10.4f", lowest, highest, (average/count));
    }
    

提交回复
热议问题