Java - Math random() 方法



描述

Java Math random() 返回一個帶有正號的 double 值,大於等於 0.0 且小於 1.0。

返回值是偽隨機選擇的,其分佈(近似)均勻分佈在該範圍內。當第一次呼叫此方法時,它會建立一個新的偽隨機數生成器,就像表示式 new java.util.Random 一樣。

此新的偽隨機數生成器此後將用於對該方法的所有呼叫,並且不會用於其他任何地方。此方法已正確同步,允許多個執行緒正確使用。但是,如果許多執行緒需要以很快的速度生成偽隨機數,則為每個執行緒擁有其自己的偽隨機數生成器可能會減少爭用。

宣告

以下是java.lang.Math.random() 方法的宣告

public static double random()

引數

返回值

此方法返回一個偽隨機 double 值,大於等於 0.0 且小於 1.0。

異常

示例:獲取 0.0 到 1.0 之間的隨機數

以下示例演示瞭如何使用 Math random() 方法獲取 0.0 到 1.0 之間的隨機數。

package com.tutorialspoint;
public class MathDemo {
   public static void main(String[] args) {

      // get two random double numbers
      double x = Math.random();
      double y = Math.random();
   
      // print the numbers and print the higher one
      System.out.println("Random number 1:" + x);
      System.out.println("Random number 2:" + y);
      System.out.println("Highest number:" + Math.max(x, y));
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Random number 1:0.5016301836409477
Random number 2:0.591827364722481
Highest number:0.591827364722481

示例:獲取 0.0 到 5.0 之間的隨機數

以下示例演示瞭如何使用 Math random() 方法獲取 0.0 到 5.0 之間的隨機數。

package com.tutorialspoint;
public class MathDemo {
   public static void main(String[] args) {

      // get two random double numbers
      double x = Math.random() * 5.0;
      double y = Math.random() * 5.0;
   
      // print the numbers and print the higher one
      System.out.println("Random number 1:" + x);
      System.out.println("Random number 2:" + y);
      System.out.println("Highest number:" + Math.max(x, y));
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Random number 1:2.9497714055410174
Random number 2:1.1016708521940748
Highest number:2.9497714055410174

示例:獲取 0.0 到 -5.0 之間的隨機數

以下示例演示瞭如何使用 Math random() 方法獲取 0.0 到 -5.0 之間的隨機數。

package com.tutorialspoint;
public class MathDemo {
   public static void main(String[] args) {

      // get two random double numbers
      double x = Math.random() * -5.0;
      double y = Math.random() * -5.0;
   
      // print the numbers and print the higher one
      System.out.println("Random number 1:" + x);
      System.out.println("Random number 2:" + y);
      System.out.println("Highest number:" + Math.max(x, y));
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Random number 1:-4.597468918068065
Random number 2:-1.1033485127978726
Highest number:-1.1033485127978726
java_lang_math.htm
廣告
© . All rights reserved.