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.