1.Math类
Math提供了数学计算的静态方法:
- abs/min/max
- pow/sqrt/exp/log/log10
- sin/cos/tan/asin/acos...
常量:
- PI=3.14159...
- E=2.71828
2.Random
Math.random()生产一个随机数:
- 0<=随机数<1
- 可用于生成某个区间的随机数
//0<=R<1
double x1 = Math.random();
//MIN <= R < MAX
long MIN = 1000;
long MAX = 9000;
double x2 = Math.random()*(MAX - MIN)+MIN;
double r = (long)x2;
Random用来创建伪随机数
- nextInt/nextLong/nextFloat...
- nextInt(N)生成不大于N的随机数
Random r = new Random();
r.nextInt();//生成下一个随机int
r.nextLong();//生成下一个随机long
r.nextFloat();//生成下一个随机float,介于0~1
r.nextDouble();//生成下一个随机double,介于0~1
r.nextInt(10);//生成0~10之间的随机数,不包括10
什么是伪随机数?
- 给定种子后伪随机数算法会生成完全相同的序列
- 不给定种子时Random使用系统当前时间戳作为种子
Random r = new Random(12345);
for(int i = 0; i < 10; i++){
System.out.println(r.nextInt(100));
}
//51,80,41,28,...
SecureRandom用来创建安全的随机数,缺点是比较慢
SecureRandom sr = new SecureRandom();
for(int i = 0; i < 10; i++){
System.out.println(sr.nextInt(100));
}
3.BigInterger
BigInterger用任意多个int[]来表示非常大的整数
BigInteger bi = new BigInteger("1234567890");
System.out.println(bi.pow(5));
4.BigDecimal
BigDecimal表示任意精度的浮点数
BigDecimal bd = new BigDecimal("123.10");
System.out.println(bd);
public class Main {
public static void main(String[] args){
//Math
System.out.println(Math.sqrt(2));
//Random
Random rnd = new Random(123456);
System.out.println(rnd.nextInt());
System.out.println(rnd.nextInt());
//SecureRandom
SecureRandom sr = new SecureRandom();
System.out.println(rnd.nextInt());
System.out.println(rnd.nextInt());
//BigInteger
BigInteger bi = new BigInteger("1234567890");
System.out.println(bi.pow(5));
//BigDecimal
BigDecimal bd = new BigDecimal("123.10");
System.out.println(bd.multiply(bd));
}
}
总结
JDK常用工具类
- Math:数学计算
- Random:生成伪随机数
- SecureRandom:生成安全的随机数
- BigInteger:表示任意大小的整数
- BigDecimal:表示任意精度的浮点数
- BigInteger和BigDecimal都继承自Number