md_files/自学/草稿.md

70 lines
2.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

下面是 Java 中 `java.util.Random` 类的简要介绍及几种最常用的用法示例。
------
## 1. 基本概念
- `Random` 是伪随机数生成器内部用线性同余法LCG产生序列。
- 如果不传 seed默认以当前时间作为种子传入相同 seed 会得到相同的“随机”序列,方便测试。
```java
import java.util.Random;
Random rnd1 = new Random(); // 随机种子
Random rnd2 = new Random(12345L); // 固定种子 -> 每次结果相同
```
------
## 2. 常用方法
| 方法 | 功能 | 返回值范围 |
| ---------------- | ----------------------- | ----------------------------------------- |
| `nextInt()` | 任意 int | `Integer.MIN_VALUE``Integer.MAX_VALUE` |
| `nextInt(bound)` | 0至 bound不含 | `[0, bound)` |
| `nextLong()` | 任意 long | 整个 long 范围 |
| `nextDouble()` | double 小数 | `[0.0, 1.0)` |
| `nextBoolean()` | 布尔值 | `true``false` |
| `nextGaussian()` | 高斯(正态)分布 | 均值 0、标准差 1 |
------
## 3. 示例代码
```java
import java.util.Random;
import java.util.stream.IntStream;
public class RandomDemo {
public static void main(String[] args) {
Random rnd = new Random(); // 随机种子
Random seeded = new Random(2025L); // 固定种子
// 1) 随机整数
int a = rnd.nextInt(); // 任意 int
int b = rnd.nextInt(100); // [0,100)
System.out.println("a=" + a + ", b=" + b);
// 2) 随机浮点数与布尔
double d = rnd.nextDouble(); // [0.0,1.0)
boolean flag = rnd.nextBoolean();
System.out.println("d=" + d + ", flag=" + flag);
// 3) 高斯分布
double g = rnd.nextGaussian(); // 均值0σ=1
System.out.println("gaussian=" + g);
// 4) 生成一组随机数流
IntStream stream = rnd.ints(5, 50, 60); // 5 个 [50,60) 的随机 ints
System.out.print("stream: ");
stream.forEach(n -> System.out.print(n + " "));
}
}
```
------
## 4. 小贴士
- 并发环境下可用 `ThreadLocalRandom.current()`,避免多线程竞争。
- 若只需加密强度随机数,请使用 `SecureRandom`