lundi 19 septembre 2016

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 x number of 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]);
        }
    }
}




Aucun commentaire:

Enregistrer un commentaire