java隨機數Reandom(簡單介紹)

來源:互聯網
上載者:User

標籤:結束   作用   區間   分享圖片   numbers   ret   new   static   數字   

簡單介紹

Java中存在著兩種Random函數

一、java.lang.Math.Random;

  調用這個Math.Random()函數能夠返回帶正號的double值,該值大於等於0.0且小於1.0,即取值範圍是[0.0,1.0)的左閉右開區間,傳回值是一個偽隨機播放的數,在該範圍內(近似)均勻分布。

二、java.util.Random

  Random()的兩種構造方法:

     1、Random():建立一個新的隨機數產生器。

     2、Random(long seed):使用單個 long 種子建立一個新的隨機數產生器。

    我們可以在構造Random對象的時候指定種子(這裡指定種子有何作用,請接著往下看)

    如:Random r1 = new Random(20);或者預設當前系統時間的毫秒數作為種子數:Random r1 = new Random();

    需要說明的是:你在建立一個Random對象的時候可以給定任意一個合法的種子數,種子數只是隨機演算法的起源數字,和產生的隨機數的區間沒有任何關係。

    Java產生隨機數需要有一個基值seed,在第一種方法中基值預設,則將系統時間作為seed。

     普通方法:

     1、public synonronized void setSeed(long seed) 該方法是設定基值seed。

     2、public int nextInt() 該方法是產生一個整型隨機數。

    3、public long nextLong() 該方法是產生一個long型隨機數。

    4、public float nextFloat() 該方法是產生一個Float型隨機數。

    6、public double nextDouble() 該方法是產生一個Double型隨機數。

    7、public synchronized double nextGoussian() 該方法是產生一個double型的Goussian隨機數。

案列:

package com.wbg;import java.lang.*;import java.util.Random;public class RandomApp {    public static void main(String args[]) {        Random ran1 = new Random();        Random ran2 = new Random(12345);//建立了兩個類Random的對象。        System.out.println("The 1st set of random numbers:");        System.out.println(" Integer:" + ran1.nextInt());        System.out.println(" Long:" + ran1.nextLong());        System.out.println(" Float:" + ran1.nextFloat());        System.out.println(" Double:" + ran1.nextDouble());        System.out.println(" Gaussian:" + ran1.nextGaussian());          //產生各種類型的隨機數        for (int i = 0; i < 5; i++) {            System.out.println(ran2.nextInt() + " ");            if (i == 2)                System.out.println();//產生同種類型的不同的隨機數。        }    }}
View Code

也可以有nextFloat等等,各種基本類型都有 Math.random也可以

比如說你想要0-10之間的隨機數

你可以這樣寫 (int)(Math.random()*10);

《JAVA產生指定範圍的隨機數》 產生機制: 產生Min-Max之間的數字 實現原理:

//不能設定為int,必須設定為long

Math.round(Math.random()*(Max-Min)+Min) long Temp; 

//產生1000到9999的隨機數

Temp=Math.round(Math.random()*8999+1000);

總結:
//第一個參數是結束數字 第二個參數是開始的數字public static int reandom(int stop,int stat ){        return (int)Math.round(Math.random()*(stat-stop)+stop);    }

 

java隨機數Reandom(簡單介紹)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.