【Java中Math類常用函式總結】
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()); //生產一個0~32之間的隨機整數 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之間的偽隨機數