random_int

random_int(int $min, int $max): int

生成密码学安全的随机整数(区间两端都含)。

C C23

C23
#include <stdio.h>

// C 标准库无密码学安全随机;读 /dev/urandom 取随机字节(Linux/macOS 通用)
static int roll_1_to_6(void) {
    FILE *f = fopen("/dev/urandom", "rb");
    unsigned char b;
    if (f == NULL) return 1;
    if (fread(&b, 1, 1, f) != 1) b = 0;
    fclose(f);
    return b % 6 + 1; // 演示用;取模有轻微偏差,生产应拒绝采样
}

int main(void) {
    int out_of_range = 0;
    int seen[7] = {0};
    for (int i = 0; i < 100; i++) {
        int v = roll_1_to_6();
        if (v < 1 || v > 6) out_of_range++;
        else seen[v] = 1;
    }
    int distinct = 0;
    for (int v = 1; v <= 6; v++) distinct += seen[v];
    printf("out_of_range=%d\n", out_of_range);
    printf("distinct>1=%s\n", distinct > 1 ? "true" : "false");
    return 0;
}
输出
out_of_range=0
distinct>1=true

C++ C++26

C++26
#include <iostream>
#include <random>

// random_device 由实现提供非确定熵源(主流平台即 CSPRNG)
static int roll_1_to_6() {
    static std::random_device device;
    return static_cast<int>(device() % 6) + 1;
}

int main() {
    int out_of_range = 0;
    bool seen[7] = {};
    for (int i = 0; i < 100; i++) {
        int v = roll_1_to_6();
        if (v < 1 || v > 6) out_of_range++;
        else seen[v] = true;
    }
    int distinct = 0;
    for (int v = 1; v <= 6; v++) distinct += seen[v];
    std::cout << "out_of_range=" << out_of_range << "\n";
    std::cout << "distinct>1=" << (distinct > 1 ? "true" : "false") << "\n";
    return 0;
}
输出
out_of_range=0
distinct>1=true

C# v11.0.100

v11.0.100
using System.Security.Cryptography;

var values = new int[100];
for (int i = 0; i < 100; i++) values[i] = RandomNumberGenerator.GetInt32(1, 7); // 上界不含,7 对应 PHP 的 (1, 6)
int outOfRange = 0;
bool[] seen = new bool[7];
foreach (int v in values) {
    if (v < 1 || v > 6) outOfRange++;
    else seen[v] = true;
}
int distinct = 0;
for (int v = 1; v <= 6; v++) {
    if (seen[v]) distinct++;
}
Console.WriteLine($"out_of_range={outOfRange}");
Console.WriteLine($"distinct>1={(distinct > 1 ? "true" : "false")}");
输出
out_of_range=0
distinct>1=true

Go v1.27.4

v1.27.4
package main

import (
	"crypto/rand"
	"fmt"
	"math/big"
)

func main() {
	outOfRange := 0
	seen := map[int]bool{}
	for i := 0; i < 100; i++ {
		n, err := rand.Int(rand.Reader, big.NewInt(6)) // [0, 6),内部拒绝采样无模偏差
		if err != nil {
			panic(err)
		}
		v := int(n.Int64()) + 1
		if v < 1 || v > 6 {
			outOfRange++
		} else {
			seen[v] = true
		}
	}
	fmt.Printf("out_of_range=%d\n", outOfRange)
	fmt.Printf("distinct>1=%v\n", len(seen) > 1)
}
输出
out_of_range=0
distinct>1=true

Java v27.0.1

v27.0.1
import java.security.SecureRandom;
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        SecureRandom random = new SecureRandom();
        int outOfRange = 0;
        Set<Integer> distinct = new HashSet<>();
        for (int i = 0; i < 100; i++) {
            int v = random.nextInt(6) + 1; // nextInt(6) 为 [0, 6),内部无模偏差
            if (v < 1 || v > 6) outOfRange++;
            else distinct.add(v);
        }
        System.out.println("out_of_range=" + outOfRange);
        System.out.println("distinct>1=" + (distinct.size() > 1));
    }
}
输出
out_of_range=0
distinct>1=true

JavaScript v26.13.1

v26.13.1
// Math.random 非密码学安全;node:crypto.randomInt 才对应 random_int
const { randomInt } = require("node:crypto");
const values = Array.from({ length: 100 }, () => randomInt(1, 7)); // 上界不含
const outOfRange = values.filter((v) => v < 1 || v > 6).length;
const distinct = new Set(values).size;
console.log(`out_of_range=${outOfRange}`);
console.log(`distinct>1=${distinct > 1}`);
输出
out_of_range=0
distinct>1=true

PHP v8.6.0

v8.6.0
// random_int 不可设定种子,输出每次运行都不同——
// 示例改为统计断言:100 个样本全部落在 [1,6](恒真)且取值多样(恒真)
$values = [];
for ($i = 0; $i < 100; $i++) {
    $values[] = random_int(1, 6);
}
$outOfRange = count(array_filter($values, function ($v) { return $v < 1 || $v > 6; }));
echo "out_of_range=$outOfRange\n";
echo "distinct>1=" . json_encode(count(array_unique($values)) > 1);
输出
out_of_range=0
distinct>1=true

Python v3.15.2

v3.15.2
# random 模块(Mersenne Twister)非密码学安全,secrets 才是
import secrets

values = [secrets.randbelow(6) + 1 for _ in range(100)]  # randbelow 内部拒绝采样
out_of_range = sum(1 for v in values if v < 1 or v > 6)
distinct = len(set(values))
print(f"out_of_range={out_of_range}")
print(f"distinct>1={distinct > 1}")
输出
out_of_range=0
distinct>1=True

Rust v1.99.1

v1.99.1
use rand::rngs::OsRng;
use rand::Rng;

fn main() {
    let mut out_of_range = 0;
    let mut seen = [false; 7];
    for _ in 0..100 {
        let v = OsRng.gen_range(1..=6); // OsRng 直连系统熵源;gen_range 内部无模偏差
        if v < 1 || v > 6 {
            out_of_range += 1;
        } else {
            seen[v as usize] = true;
        }
    }
    let distinct = seen.iter().filter(|&&b| b).count();
    println!("out_of_range={}", out_of_range);
    println!("distinct>1={}", distinct > 1);
}
输出
out_of_range=0
distinct>1=true

TypeScript v26.13.1

v26.13.1
// Math.random 非密码学安全;node:crypto.randomInt 才对应 random_int
import { randomInt } from "node:crypto";
const values = Array.from({ length: 100 }, () => randomInt(1, 7)); // 上界不含
const outOfRange = values.filter((v) => v < 1 || v > 6).length;
const distinct = new Set(values).size;
console.log(`out_of_range=${outOfRange}`);
console.log(`distinct>1=${distinct > 1}`);
输出
out_of_range=0
distinct>1=true

语言差异说明

C:rand() 非密码学安全(可预测);示例读 /dev/urandom(注释点明取模偏差——256 % 6 ≠ 0 使小值略占优,生产应拒绝采样或平台 API:Linux getrandom(2)、macOS arc4random_uniform)。

C++:random_device 是实现定义的非确定源(主流平台即 CSPRNG,示例);mt19937 等引擎是确定性伪随机(可设种子),不用于密码学。

C#:Random 类非密码学安全(时间种子可预测);RandomNumberGenerator.GetInt32(min, max+1) 是正确等价物(示例注释点明上界不含的差异)。

Go:math/rand 非密码学安全;crypto/rand.Int(Reader, n) 返回 [0, n) 大整数(示例),内部拒绝采样无模偏差;错误必须处理(熵源不可用时返回 err)。

Java:java.util.Random 非密码学安全(48 位种子可暴力);SecureRandom.nextInt(6)+1(示例)无模偏差;默认实现平台相关(Linux 常为 NativePRNG)。

JavaScript:Math.random 非密码学安全且不可设种子;Node 的 crypto.randomInt(1, 7)(示例,上界不含)、浏览器的 crypto.getRandomValues 才是密码学安全。

PHP:random_int(7.0+)聚合系统熵源,失败抛异常而非静默降级;min/max 两端都含(与 C# /JS 的上界不含 API 相反,示例各语言已对齐)。输出确定性说明:真随机每次运行结果不同,直接打印随机值会让校验比对必然失败——示例改为统计断言:区间合法性由 API 契约保证恒真;100 次全同的概率仅 6/6^100 ≈ 3.8×10⁻⁷⁷,多样性断言视为恒真。

Python:random 模块是 Mersenne Twister(可预测、可设种子);secrets.randbelow(6)+1(示例)是文档钦定的密码学安全写法,内部拒绝采样。

Rust:rand 的 OsRng(示例)直连操作系统熵源(getrandom(2)/arc4random);StdRng/SmallRng 是可种子化伪随机,不作密码学用途;gen_range 内部拒绝采样。

TypeScript:同 JavaScript;浏览器端 crypto.getRandomValues(new Uint32Array(1))[0] % 6 + 1 有模偏差,推荐 randomInt 等价实现或拒绝采样。