简体   繁体   English

如何使随机性检查器更有效

[英]How to make a randomness checker more efficient

Hello I'm trying to make a program to check the distribution of random numbers in Java. 您好,我正在尝试编写一个程序来检查Java中随机数的分布。 The idea of the program is to (using Java) generate many random numbers and then see how many numbers are in each of the following ranges: 该程序的想法是(使用Java)生成许多随机数,然后查看以下各个范围内的数字:

  • 0.0 - 0.1 0.0-0.1
  • 0.1 - 0.2 0.1-0.2
  • 0.2 - 0.3 0.2-0.3

    ... ...

  • 0.8 - 0.9 0.8-0.9

  • 0.9 - 1.0 0.9-1.0

I have managed to do this but I was wondering if there is a more efficient/quicker way to do it. 我已经做到了,但是我想知道是否有更有效/更快的方法来做到这一点。

public class RandomTest
{
    //Get value of digit in tenths place of double
    public static int getFirstDecimal(double num) 
    {
        return (int) (num * 10);
    }

    public static void main(String args[])
    {
        int[] results = new int[10]; //Results array

        double x; //Random number holder
        int genNum; //Number of random numbers to generate

        for(genNum = 0; genNum < 10000; genNum++)
        {
            x = Math.random();
            results[getFirstDecimal(x)]++;
        }

        for(int i = 0; i < 10; i++)
        {
            System.out.println(results[i]);
        }
    }
}

Try this if you really want to shorten the code: 如果您确实想缩短代码,请尝试以下操作:

int[] results = new int[10];
IntStream.range(1, 10000).forEach(s -> results[getFirstDecimal(Math.random())]++);
Arrays.stream(results).forEach(System.out::println);

IntStream from 1 to 10000 is just like a for-loop, and for each of those numbers you do the same thing you did, increment value at corresponding index in an array. 从1到10000的IntStream就像一个for循环,对于这些数字中的每一个,您都执行相同的操作,则在数组中的相应索引处递增值。 Then you just print that array, also using streams. 然后,您也可以使用流打印该数组。 Ofcourse you need to keep your getFirstDecimal method, because this code is using this method inside, you could extract code from that method to the stream, but it would look ugly, I think it's better to have a separate method for that. 当然,您需要保留getFirstDecimal方法,因为此代码在内部使用此方法,您可以将代码从该方法提取到流中,但是看起来很难看,我认为最好为此使用一个单独的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM