本文介绍了Java中随机生成器的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从事涉及模拟 802.11 MAC 协议的无线项目.我在其中使用了随机生成器.问题是我们得到了不平滑的图形.我相信这个错误是因为随机生成器.为了测试,我运行了以下代码,该代码生成 0 到 19 之间的 100 个随机数.如果您仔细查看输出,会发现有几个相同或非常接近的连续数字(例如 17、15、16...或 1、1,……).它会导致在我们的模拟中发生碰撞,并且相应的吞吐量在该点下降(即变得蠕动形状).在这种情况下,增加模拟运行时间并没有多大帮助.

I am working on wireless project which involves simulating 802.11 MAC protocol.I used random generator in it.The problem is that we are getting wriggly not smooth graphs.I believe the bug is because of random generator. To test I ran the following code which generates 100 random numbers between 0 and 19. If you carefully look at the output, there are several consecutive numbers which are identical or very close (e.g. 17, 15, 16... or 1, 1, ...). It causes collisions to happen in our simulation and the corresponding throughput to fall at that point (i.e. getting wrigglyshape). In this case increasing simulation run time does not help that much.

谁能帮我弄清楚如何在 Java 循环中生成 n 个真正随机的随机数(没有那种模式)?

Can anyone help me figure out how to generate n random numbers in a loop in Java that are really random (without that kind of patterns)?

这是要尝试的代码:

import java.util.Random;

public class RandomTest {

    public static void main(String[] args){

        int [] counter = new int [20];

        Random generator = new Random();
        int randomIndex = 0;

        for (int i=0; i<100; i++){

            randomIndex = generator.nextInt(20);
            counter[randomIndex]++;
            System.out.println(randomIndex);
        }
    }
}

推荐答案

随机并不意味着每次都不同.偶尔会出现重复或相似的值,尤其是当您从如此小的范围(20 个值)中选择数字时.

Random doesn't mean different every time. Occasional repeated or similar values are expected, especially when you are choosing numbers from such a small range (20 values).

如果您确实希望每个数字与前面的数字不同,那么您必须自己编程.最简单的方法之一(但不是最有效)是拒绝与前一个随机数距离 x 范围内的随机数并选择另一个数字 - 重复直到得到您满意的数字.

If you do want each number to be different from the preceding number then you have to program that yourself. One of the simplest ways (but not most efficient) is to reject a random number that is within distance x of the previous random number and choose another number - repeat until you get a number you are happy with.

这篇关于Java中随机生成器的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 04:43