Math.random() versus Random.nextInt(int)

后端 未结 4 1422
灰色年华
灰色年华 2020-11-22 07:21

What is the difference between Math.random() * n and Random.nextInt(n) where n is an integer?

4条回答
  •  春和景丽
    2020-11-22 08:13

    According to this example Random.nextInt(n) has less predictable output then Math.random() * n. According to [sorted array faster than an unsorted array][1] I think we can say Random.nextInt(n) is hard to predict.

    usingRandomClass : time:328 milesecond.

    usingMathsRandom : time:187 milesecond.

    package javaFuction;
    import java.util.Random;
    public class RandomFuction 
    {
        static int array[] = new int[9999];
        static long sum = 0;
        public static void usingMathsRandom() {
            for (int i = 0; i < 9999; i++) {
             array[i] = (int) (Math.random() * 256);
           }
    
            for (int i = 0; i < 9999; i++) {
                for (int j = 0; j < 9999; j++) {
                    if (array[j] >= 128) {
                        sum += array[j];
                    }
                }
            }
        }
    
        public static void usingRandomClass() {
            Random random = new Random();
            for (int i = 0; i < 9999; i++) {
                array[i] = random.nextInt(256);
            }
    
            for (int i = 0; i < 9999; i++) {
                for (int j = 0; j < 9999; j++) {
                    if (array[j] >= 128) {
                        sum += array[j];
                    }
                }
    
            }
    
        }
    
        public static void main(String[] args) {
            long start = System.currentTimeMillis();
            usingRandomClass();
            long end = System.currentTimeMillis();
            System.out.println("usingRandomClass " + (end - start));
            start = System.currentTimeMillis();
            usingMathsRandom();
            end = System.currentTimeMillis();
            System.out.println("usingMathsRandom " + (end - start));
    
        }
    
    }
    

提交回复
热议问题