//绝对值值运算: Math.abs(18.999); //返回19.999这个数的绝对值 Math.abs(-12.58); // 返回-12.58这个数的绝对值,为12.58 //取值运算: Math.signum(x); //若是x大于0则返回1.0,小于0则返回-1.0,等于0则返回0 //取整运算: Math.ceil(-13.56); //返回最近的且大于这个数的整数, 为14.0 Math.floor(-13.56); //返回最近的且小于这个数的整数, 为13.0 Math.rint(13.56); ////返回最接近这个数的整数,若是恰好居中,则取偶数,为14 //对数运算: Math.log10(100); // 以10为底数的100的对数 ,为2 //指数运算: Math.expm1(x); //e的x次幂 - Math.pow(a,b); //a的b次幂 Math.scalb(x, y); //x*(2的y次幂) //二次方根运算: Math.sqrt(x); //x的二次方根 //三次方根运算: Math.cbrt(x); //x的三次方根 //返回较大值和较小值: Math.max(x, y); //返回x、y中较大的数 Math.min(x, y); //返回x、y中较小的数 //三角函数运算: Math.sin(α); //sin(α)的值 Math.cos(α); //cos(α)的值 Math.tan(α); //tan(α)的值 //求角运算: Math.asin(x/z); //返回角度值[-π/2,π/2] arc sin(x/z) Math.acos(y/z); //返回角度值[0~π] arc cos(y/z) Math.atan(y/x); //返回角度值[-π/2,π/2] arctan(y/x) //随机值运算: Math.random(); //随机返回[0,1)之间的无符号double值
Random 是一个线程安全类,理论上能够经过它同时在多个线程中得到互不相同的随机数,可是在多线程的场景下须要多个线程竞争同一个原子变量的更新操做,性能不佳。java
多线程性能参见:https://www.imooc.com/article/29739数组
有两种构造方法:安全
public static void main(String[] args) { Random rand = new Random(); //随机boolean值 System.out.println(rand.nextBoolean()); //true //随机填充byte数组 byte[] buffer = new byte[16]; rand.nextBytes(buffer); //[106, -85, 66, 108, 93, -22, 114, -67, -97, -99, 34, 126, 3, 66, -25, 59] System.out.println(Arrays.toString(buffer)); //随机[0.0, 1.0) 区间的double值 System.out.println(rand.nextDouble()); //0.6032052834419511 //随机[0.0, 1.0) 区间的float值 System.out.println(rand.nextFloat()); //0.19521767 //随机int范围的整数 System.out.println(rand.nextInt()); //-1557426129 //随机生成[0, 15)区间的整数 System.out.println(rand.nextInt(15)); //6 //随机long范围整数 System.out.println(rand.nextLong()); //868994934892445287 }
ThreadLocalRandon 类是 JDK 1.7
新增的一个类,它是 Random 的加强版,在并发访问的环境下,使用它来代替 Random 能够减小多线程资源竞争,最终保证系统具备更好的线程安全性。ThreadLocalRandom 类提供了一个静态方法来获取当前线程的随机数生成器:多线程
ThreadLocalRandom rand = ThreadLocalRandom.current();
ThreadLocalRandom 方法的用法和 Random 基本相似,增长几个功能:并发
//返回一个boolean类型的随机数 public boolean nextBoolean(); //随机填充一个byte数组 public void nextBytes(byte[] bytes); //返回一个[0.0,1.0)范围的float随机数 public float nextFloat(); //返回一个[0.0,1.0)范围的double随机数 public double nextDouble(); //返回一个[0.0-bound)之间的double随机数 public double nextDouble(double bound); //返回一个[origin-bound)之间的随机数 public double nextDouble(double origin, double bound); //返回一个整型的伪随机数 public int nextInt(); //返回一个[0,bound)之间的随机数 public int nextInt(int bound); //返回一个[origin,bound)之间的随机数 public int nextInt(int origin, int bound); //返回一个long型随机数 public long nextLong(); //返回一个[0,bound)之间的随机数 public long nextLong(long bound); //返回一个[origin,bound)之间的随机数 public long nextLong(long origin, long bound);