Java - StrictMath random() 方法



描述

Java StrictMath random() 方法返回一個帶有正號的雙精度值,大於或等於 0.0,小於 1.0。

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

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

宣告

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

public static double random()

引數

返回值

此方法返回一個大於或等於 0.0 且小於 1.0 的偽隨機雙精度數。

異常

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

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

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

      // get two random double numbers
      double x = StrictMath.random();
      double y = StrictMath.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:" + StrictMath.max(x, y));
   }
}

輸出

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

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

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

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

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

      // get two random double numbers
      double x = StrictMath.random() * 5.0;
      double y = StrictMath.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:" + StrictMath.max(x, y));
   }
}

輸出

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

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

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

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

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

      // get two random double numbers
      double x = StrictMath.random() * -5.0;
      double y = StrictMath.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:" + StrictMath.max(x, y));
   }
}

輸出

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

Random number 1:-4.597468918068065
Random number 2:-1.1033485127978726
Highest number:-1.1033485127978726
java_lang_strictmath.htm
廣告