Java.lang.StrictMath 类

java.lang.StrictMath.random() 方法返回范围 [0.0, 1.0) 内的双精度值。返回的值是从该范围的均匀分布(近似)中伪随机选择的。

要生成不同范围内的随机数,可以使用random()。例如 -

  • 要生成 [0.0, 10.0) 范围内的随机数,可以使用表达式 random()*10。
  • 要生成 [0.0, 10.0) 范围内的随机数。范围 [-1.0, 1.0),可以使用表达式 random()*2 - 1。

语法

public static double random()

参数

不需要参数。

返回值

返回范围 [0.0, 1.0) 内的伪随机双精度值。

异常

无。

示例:

在下面的示例中,random()方法用于生成范围内的伪随机双精度数[0.0, 1.0)。

import java.lang.*;

public class MyClass {
 public static void main(String[] args) {
  System.out.println(StrictMath.random());   
  System.out.println(StrictMath.random());
  System.out.println(StrictMath.random());     
 }
}

上述代码的输出将是:

0.2778296598497003
0.6421976830440985
0.18591614847496474

示例:

在下面的示例中,方法用于生成范围 [0.0, 10.0) 内的伪随机双精度值。

import java.lang.*;

public class MyClass {
 public static void main(String[] args) {
  System.out.println(StrictMath.random()*10);   
  System.out.println(StrictMath.random()*10);
  System.out.println(StrictMath.random()*10);     
 }
}

上述代码的输出将是:

3.925911027583192
4.588044289363738
3.115186794654875

示例:

以同样的方式,它可以用于生成范围 [-1.0, 1.0) 内的伪随机双精度值。

import java.lang.*;

public class MyClass {
 public static void main(String[] args) {
  System.out.println(StrictMath.random()*2-1);   
  System.out.println(StrictMath.random()*2-1);
  System.out.println(StrictMath.random()*2-1);     
 }
}

上述代码的输出将是:

p>
0.616550701127146
0.5330712637034409
-0.9722965205765486