Java中比較常用的幾個數(shù)學(xué)公式的總結(jié):
//取整,返回小于目標(biāo)函數(shù)的最大整數(shù),如下將會返回-2 Math.floor(-1.8); //取整,返回發(fā)育目標(biāo)數(shù)的最小整數(shù) Math.ceil() //四舍五入取整 Math.round() //計(jì)算平方根 Math.sqrt() //計(jì)算立方根 Math.cbrt() //返回歐拉數(shù)e的n次冪 Math.exp(3); //計(jì)算乘方,下面是計(jì)算3的2次方 Math.pow(3,2); //計(jì)算自然對數(shù) Math.log(); //計(jì)算絕對值 Math.abs(); //計(jì)算最大值 Math.max(2.3,4.5); //計(jì)算最小值 Math.min(,); //返回一個偽隨機(jī)數(shù),該數(shù)大于等于0.0并且小于1.0 Math.random
Random類專門用于生成一個偽隨機(jī)數(shù),它有兩個構(gòu)造器:一個構(gòu)造器使用默認(rèn)的種子(以當(dāng)前時間作為種子),另一個構(gòu)造器需要程序員顯示的傳入一個long型整數(shù)的種子。
Random比Math的random()方法提供了更多的方式來生成各種偽隨機(jī)數(shù)。
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("隨機(jī)布爾數(shù)" + rand.nextBoolean());     byte[] buffer = new byte[16];     rand.nextBytes(buffer);     //生產(chǎn)一個含有16個數(shù)組元素的隨機(jī)數(shù)數(shù)組     System.out.println(Arrays.toString(buffer));          System.out.println("rand.nextDouble()" + rand.nextDouble());          System.out.println("Float浮點(diǎn)數(shù)" + rand.nextFloat());          System.out.println("rand.nextGaussian" + rand.nextGaussian());          System.out.println("" + rand.nextInt());          //生產(chǎn)一個0~32之間的隨機(jī)整數(shù)     System.out.println("rand.nextInt(32)" + rand.nextInt(32));          System.out.println("rand.nextLong" + rand.nextLong());   }  } 為了避免兩個Random對象產(chǎn)生相同的數(shù)字序列,通常推薦使用當(dāng)前時間作為Random對象的種子,代碼如下:
Random rand = new Random(System.currentTimeMillis());
在java7中引入了ThreadLocalRandom
在多線程的情況下使用ThreadLocalRandom的方式與使用Random基本類似,如下程序?片段示范了ThreadLocalRandom的用法:
首先使用current()產(chǎn)生隨機(jī)序列之后使用nextCXxx()來產(chǎn)生想要的偽隨機(jī)序列:
ThreadLocalRandom trand= ThreadLocalRandom.current(); int val = rand.nextInt(4,64);
產(chǎn)生4~64之間的偽隨機(jī)數(shù)
以上就是小編為大家?guī)淼幕贘ava中Math類的常用函數(shù)總結(jié)的全部內(nèi)容了,希望對大家有所幫助,多多支持武林網(wǎng)~
新聞熱點(diǎn)
疑難解答
圖片精選