Java 的 Math 包含了用于執(zhí)行基本數(shù)學(xué)運(yùn)算的屬性和方法,如初等指數(shù)、對(duì)數(shù)、平方根和三角函數(shù)。
Math 的方法都被定義為 static 形式,通過 Math 類可以直接調(diào)用。
Math.PI
表示 π(圓周率)。
Math.E
表示 e(自然對(duì)數(shù))。
隨機(jī)數(shù)
Math.random() 生成一個(gè)0~1的隨機(jī)數(shù),類型為double,包括0但不包括1。
for(int i=0; i<3; i++){
System.out.println(Math.random());
}
Math.random() 源碼(Java7):
private static Random randomNumberGenerator;
private static synchronized Random initRNG() {
Random rnd = randomNumberGenerator;
return (rnd == null) ? (randomNumberGenerator = new Random()) : rnd;
}
public static double random() {
Random rnd = randomNumberGenerator;
if (rnd == null) rnd = initRNG();
return rnd.nextDouble();
}
random() 內(nèi)部使用了一個(gè) Random 類型的靜態(tài)變量 randomNumberGenerator,實(shí)際是調(diào)用該變量的 nextDouble() 方法。
取最值
- min / max
static int min(int x,int y)
static int max(int x,int y)
算術(shù)進(jìn)位
- ceil
Math.ceil() 返回大于或等于參數(shù)的最小整數(shù) double 。
- floor
Math.floor() 返回小于或等于參數(shù)的最大整數(shù)double`。
- rint
Math.rint() 五舍六入取整,返回 double 值。
- round
Math.round() 四舍五入取整,參數(shù) double 時(shí)返回 long 值,float 時(shí)返回 int 值。