Java Math.random() 亂數

Math.random() 用於產生亂數,回傳 0.0(含)到 1.0(不含)之間的 double 值。

基本用法

// 產生 [0.0, 1.0) 之間的亂數
double random = Math.random();
System.out.println(random);  // 例如:0.7231456...

產生指定範圍亂數

整數亂數

// 0 到 9 的整數
int n = (int) (Math.random() * 10);

// 1 到 10 的整數
int n = (int) (Math.random() * 10) + 1;

// min 到 max 的整數(含兩端)
public static int randomInt(int min, int max) {
    return (int) (Math.random() * (max - min + 1)) + min;
}

System.out.println(randomInt(1, 100));  // 1 到 100 之間

浮點數亂數

// 0.0 到 100.0 之間
double d = Math.random() * 100;

// min 到 max 之間
public static double randomDouble(double min, double max) {
    return Math.random() * (max - min) + min;
}

System.out.println(randomDouble(1.0, 10.0));

Random 類別

import java.util.Random;

Random random = new Random();

// 整數
int i = random.nextInt();           // 全範圍 int
int bounded = random.nextInt(100);  // 0 到 99
int ranged = random.nextInt(10, 20); // 10 到 19(Java 17+)

// 其他類型
long l = random.nextLong();
double d = random.nextDouble();
float f = random.nextFloat();
boolean b = random.nextBoolean();

// 使用種子(可重現結果)
Random seeded = new Random(12345);

ThreadLocalRandom(多執行緒)

import java.util.concurrent.ThreadLocalRandom;

// 多執行緒環境建議使用
int n = ThreadLocalRandom.current().nextInt(1, 101);  // 1 到 100
double d = ThreadLocalRandom.current().nextDouble(0, 100);

SecureRandom(安全亂數)

import java.security.SecureRandom;

// 密碼學安全的亂數
SecureRandom secure = new SecureRandom();
int n = secure.nextInt(100);

// 產生隨機位元組
byte[] bytes = new byte[16];
secure.nextBytes(bytes);

實用範例

隨機選擇陣列元素

public static <T> T randomElement(T[] array) {
    int index = (int) (Math.random() * array.length);
    return array[index];
}

String[] colors = {"紅", "橙", "黃", "綠", "藍"};
System.out.println(randomElement(colors));

洗牌演算法

public static void shuffle(int[] array) {
    Random random = new Random();
    for (int i = array.length - 1; i > 0; i--) {
        int j = random.nextInt(i + 1);
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

擲骰子

public static int rollDice() {
    return (int) (Math.random() * 6) + 1;
}

System.out.println("擲出: " + rollDice());

產生隨機密碼

public static String generatePassword(int length) {
    String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    StringBuilder password = new StringBuilder();
    SecureRandom random = new SecureRandom();
    
    for (int i = 0; i < length; i++) {
        int index = random.nextInt(chars.length());
        password.append(chars.charAt(index));
    }
    return password.toString();
}

System.out.println(generatePassword(12));

比較

方法執行緒安全安全性速度
Math.random()
Random
ThreadLocalRandom
SecureRandom

重點整理

  • Math.random() 回傳 [0.0, 1.0) 的 double
  • 一般用途使用 Random 類別更方便
  • 多執行緒環境使用 ThreadLocalRandom
  • 安全相關用途使用 SecureRandom
  • 使用種子可以產生可重現的亂數序列