我正在为android编写一个单词学习应用程序。Android:随机数不是很随机
要获得随机字我用:
Random rnd = new Random();
final int rnd.nextInt(WordsNumber);
为了得到随机的方向(秀字或显示翻译)我使用:
Random rnd = new Random();
final boolean dir.nextBoolean();
但我看到,一个字都不能均匀分布。 我用17个字测试应用程序。 有些词显示10次,有些只显示一次。 同样的问题是与方向。它经常发生,连续第五次方向是相同的。
也许有人知道,如何让分配更平等的话?
UPD: 我写了一个测试应用程序。它产生于按钮新号码点击:
public class About extends Activity
{
final int N = 10;
int[] results;
Random rnd;
int total;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
results = new int[N];
for (int i = 0; i < N; i++)
{
results[i] = 0;
}
rnd = new Random();
total = 0;
}
public void GenerateNumber(View view)
{
int number = rnd.nextInt(N);
results[number]++;
total++;
String output = new String();
TextView txt = (TextView)findViewById(R.id.text1);
output += "Total numbers: " + String.valueOf(total) + "\n";
for (int i = 0; i < N; i++)
{
output += String.valueOf(i) + ": " + String.valueOf(results[i]) + "\n";
}
txt.setText(output);
}
}
以下是测试结果:
也许,与N = 10000这将是平等的......但我的应用程序是个蹩脚的安慰。
最有可能是由Java相当于[C# - 随机数生成器只生成一个随机数]引起的(http://stackoverflow.com/questions/767999/random-number-generator-only-generating-one-random-number/768001#768001) –
让我想起[this](http://xkcd.com/221/)其中一个... – tilpner
@StackOverflowException先生,您为我创造了一天。 –