java 如何在不使用 Math.Random 的情况下生成随机数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13442611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I generate a random number without use of Math.Random?
提问by John Smith
My project entails that I create a basic number guessing game that uses the JOptionPane and does not use Math.Random to create the random value. How would you go about doing this? I've completed everything except the random number generator. Thanks!
我的项目需要我创建一个使用 JOptionPane 并且不使用 Math.Random 来创建随机值的基本猜数游戏。你会怎么做?除了随机数生成器,我已经完成了所有的工作。谢谢!
回答by Frank
Here the code for a Simple random generator:
这是简单随机生成器的代码:
public class SimpleRandom {
/**
* Test code
*/
public static void main(String[] args) {
SimpleRandom rand = new SimpleRandom(10);
for (int i = 0; i < 25; i++) {
System.out.println(rand.nextInt());
}
}
private int max;
private int last;
// constructor that takes the max int
public SimpleRandom(int max){
this.max = max;
last = (int) (System.currentTimeMillis() % max);
}
// Note that the result can not be bigger then 32749
public int nextInt(){
last = (last * 32719 + 3) % 32749;
return last % max;
}
}
The code above is a "Linear congruential generator (LCG)", you can find a good description of how it works here.
上面的代码是一个“线性同余生成器(LCG)”,你可以在这里找到它是如何工作的很好的描述。
Disclamer:
免责声明:
The code above is designed to be used for research only, and not as a replacement to the stock Random or SecureRandom.
上面的代码仅用于研究,不能替代股票 Random 或 SecureRandom。
回答by Emmanuel Ulloa
In JavaScript using the Middle-square method.
在 JavaScript 中使用 Middle-square 方法。
var _seed = 1234;
function middleSquare(seed){
_seed = (seed)?seed:_seed;
var sq = (_seed * _seed) + '';
_seed = parseInt(sq.substring(0,4));
return parseFloat('0.' + _seed);
}
回答by Frank
If you don't like the Math.Random you can make your own Randomobject.
如果您不喜欢 Math.Random,您可以制作自己的Random对象。
import:
进口:
import java.util.Random;
code:
代码:
Random rand = new Random();
int value = rand.nextInt();
If you need other types instead of int, Random will provide methods for boolean, double, float, long, byte.
如果您需要其他类型而不是 int,Random 将提供 boolean、double、float、long、byte 的方法。
回答by mikeslattery
You could use java.security.SecureRandom. It has better entropy.
您可以使用java.security.SecureRandom。它具有更好的熵。
Also, hereis code from the book Data Structures and Algorithm Analysis in Java. It uses the same algorithm as java.util.Random.
此外,这里是《Java 中的数据结构和算法分析》一书中的代码。它使用与 java.util.Random 相同的算法。