产生随机数的几种方法
第一种
Math.random() 这种方法返回的是随机的,带正的double值,该值得范围是【0.0,1.0),左闭右开。
可以用 int(Math.random()*6)先进行取值的扩大,变成了【0.0,6.0)之间的double值,在强制转换成整形,即为0-5之间的整数。
第二种
JDK自带的Random类
package test2;
import java.util.Arrays;
import java.util.Random;
public class Random3 {
public static void main(String[] args) {
Random rand = new Random();
System.out.println("rand.nextBoolean():" + rand.nextBoolean());
byte[] buffer = new byte[16];
rand.nextBytes(buffer);
System.out.println(Arrays.toString(buffer));
//生成0.0~1.0之间的伪随机double数
System.out.println("rand.nextDouble():" + rand.nextDouble());
//生成0.0~1.0之间的伪随机float数
System.out.println("rand.nextFloat():" + rand.nextFloat());
//生成平均值是 0.0,标准差是 1.0的伪高斯数
System.out.println("rand.nextGaussian():" + rand.nextGaussian());
//生成一个处于long整数取值范围的伪随机整数
System.out.println("rand.nextInt():" + rand.nextInt());
//生成0~26之间的伪随机整数
System.out.println("rand.nextInt(26):" + rand.nextInt(26));
//生成一个处于long整数取值范围的伪随机整数
System.out.println("rand.nextLong():" + rand.nextLong());
}
}
在这种方法下,相同”种子(seed)”的Random对象会生成相同的随机数,下面是例子
package test;
import java.util.Random;
public class TestSeed {
public static void main(String[] args) {
// TODO Auto-generated method stub
Random r1 = new Random(50);
System.out.println("第一个种子为50的Random对象");
System.out.println("r1.nextBoolean():\t" + r1.nextBoolean());
System.out.println("r1.nextInt():\t\t" + r1.nextInt());
System.out.println("r1.nextDouble():\t" + r1.nextDouble());
System.out.println("r1.nextGaussian():\t" + r1.nextGaussian());
System.out.println("---------------------------");
Random r2 = new Random(50);
System.out.println("第二个种子为50的Random对象");
System.out.println("r2.nextBoolean():\t" + r2.nextBoolean());
System.out.println("r2.nextInt():\t\t" + r2.nextInt());
System.out.println("r2.nextDouble():\t" + r2.nextDouble());
System.out.println("r2.nextGaussian():\t" + r2.nextGaussian());
System.out.println("---------------------------");
Random r3 = new Random(100);
System.out.println("种子为100的Random对象");
System.out.println("r3.nextBoolean():\t" + r3.nextBoolean());
System.out.println("r3.nextInt():\t\t" + r3.nextInt());
System.out.println("r3.nextDouble():\t" + r3.nextDouble());
System.out.println("r3.nextGaussian():\t" + r3.nextGaussian());
Random r4 = new Random(System.currentTimeMillis());
System.out.println("以当前时间为种子的Random对象");
System.out.println("r3.nextBoolean():\t" + r4.nextBoolean());
System.out.println("r3.nextInt():\t\t" + r4.nextInt());
System.out.println("r3.nextDouble():\t" + r4.nextDouble());
System.out.println("r3.nextGaussian():\t" + r4.nextGaussian());
}
}
结果截图为
所以通常以当前时间为”种子”的方法生成较好的随机数
Random random=new Random(System.currenTimeMillis());