简体   繁体   中英

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. 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:

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

    ...

  • 0.8 - 0.9

  • 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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