Java中Math类常用函数总结

来源:互联网 发布:农村淘宝下载官网 编辑:程序博客网 时间:2024/05/29 23:45

Java中比较常用的几个数学公式的总结:

 //取整,返回小于目标函数的最大整数,如下将会返回-2      Math.floor(-1.8);    //取整,返回发育目标数的最小整数      Math.ceil()    //四舍五入取整      Math.round()    //计算平方根      Math.sqrt()    //计算立方根      Math.cbrt()    //返回欧拉数e的n次幂      Math.exp(3);    //计算乘方,下面是计算3的2次方      Math.pow(3,2);    //计算自然对数      Math.log();    //计算绝对值      Math.abs();    //计算最大值      Math.max(2.3,4.5);    //计算最小值      Math.min(,);    //返回一个伪随机数,该数大于等于0.0并且小于1.0      Math.random

Random类专门用于生成一个伪随机数,它有两个构造器:一个构造器使用默认的种子(以当前时间作为种子),另一个构造器需要程序员显示的传入一个long型整数的种子。

Random比Math的random()方法提供了更多的方式来生成各种伪随机数。

e.g

   import java.util.Arrays;    import java.util.Random;    public class RandomTest {        /**          * @param args          */        public static void main(String[] args) {            // TODO Auto-generated method stub              Random rand = new Random();            System.out.println("随机布尔数" + rand.nextBoolean());            byte[] buffer = new byte[16];            rand.nextBytes(buffer);            //生产一个含有16个数组元素的随机数数组              System.out.println(Arrays.toString(buffer));            System.out.println("rand.nextDouble()" + rand.nextDouble());            System.out.println("Float浮点数" + rand.nextFloat());            System.out.println("rand.nextGaussian" + rand.nextGaussian());            System.out.println("" + rand.nextInt());            //生产一个032之间的随机整数              System.out.println("rand.nextInt(32)" + rand.nextInt(32));            System.out.println("rand.nextLong" + rand.nextLong());        }    }

为了避免两个Random对象产生相同的数字序列,通常推荐使用当前时间作为Random对象的种子,代码如下:

Random rand = new Random(System.currentTimeMillis());

在java7中引入了ThreadLocalRandom

在多线程的情况下使用ThreadLocalRandom的方式与使用Random基本类似,如下程序·片段示范了ThreadLocalRandom的用法:

首先使用current()产生随机序列之后使用nextCXxx()来产生想要的伪随机序列:

    ThreadLocalRandom trand= ThreadLocalRandom.current();    int val = rand.nextInt(4,64);

产生4~64之间的伪随机数

本文地址:http://liuyanzhao.com/3150.html

转载请注明

0 0