基於Java中Math類的常用函數總結_java

來源:互聯網
上載者:User

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之間的偽隨機數

以上就是小編為大家帶來的基於Java中Math類的常用函數總結的全部內容了,希望對大家有所協助,多多支援雲棲社區~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.