1. 程式人生 > >Java Math 數學工具類

Java Math 數學工具類

Math類

包含用於執行基本數學運算的方法,如絕對值,對數,平方根和三角函式。它是一個final類,其中定義的都是一些常量和景甜方法。

常用方法如下:

補充:

1、Math.abs() 計算絕對值

package com.Java.Base;
public class Test_Math {
	public static void main(String[] args) {	
		//Math常用方法
		//sqrt開平方
		System.out.println("Math.sqrt(4)="+Math.sqrt(4));		
		//ceil向上取整
		System.out.println("Math.ceil(3.3)="+Math.ceil(3.3));
		//floor向下取整
		System.out.println("Math.floor(3.3)="+Math.floor(3.3));
		//pow乘方
		System.out.println("Math.pow(2,3)="+Math.pow(2,3));		
		//round四捨五入
		System.out.println("Math.round(2.3)="+Math.round(2.3));
		System.out.println("Math.round(2.5)="+Math.round(2.5));
		//random()  [0,1)
		System.out.println("Math.random()="+Math.random());
		
	}

}

執行結果:

 

java 三種產生隨機數方法


1. System.currentTimeMillis() 得到long型數字
2. Math.random()   取值範圍為[0,1)
3. Random類產生一個隨機數

Random類中實現的隨機演算法是偽隨機的,即有規律的隨機。隨機時,隨機演算法的起源數字稱為種子數seed,在種子數的基礎上進行一定的變換,從而產生需要的隨機數字。相同種子數的Random物件,相同次數生成的隨機數字相同。

構造方法:

1、public Random()        預設種子數是不一樣的

2、public Random(long seed)  自行設定seed

常用函式:

1、public void nextBytes(byte[] bytes)

2、public int nextInt()

3、public int nextInt(int n)   產生[0,5)之間的隨機正數

4、public boolean nextBoolean()

5、public float nextFloat()

6、public double nextDouble()

例項:

package com.Java.Base;

import java.util.Arrays;
import java.util.Random;

public class Test_Random {
	public static void main(String[] args) {
		Random r=new Random();
		byte[] b = new byte[5];
		r.nextBytes(b);
		System.out.println(Arrays.toString(b));	
		System.out.println(r.nextInt(5));
		
	}
}

結果: