简体   繁体   English

生成随机长长 C++

[英]Generate random long long C++

int generator int生成器

I currently generate deterministic pseudo-random int s using this code:我目前使用以下代码生成确定性伪随机int

#include <chrono>
#include <ctime>
#include <random>
#include <stdint.h>

const uint32_t CurrentTime = static_cast<uint32_t>(std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now().time_since_epoch()).count());

std::mt19937 Mersenne = std::mt19937(static_cast<std::mt19937::result_type>(CurrentTime));

int Min = 3;
int Max = 6;
std::uniform_int_distribution<> Distribution(Min, Max-1);

int Result = Distribution(Mersenne);

The problem问题

There's two problems with this:这有两个问题:

  1. The parameters for Distribution must be int s. Distribution的参数必须是int s。
  2. The result from Distribution(Mersenne) is an int . Distribution(Mersenne)的结果是一个int

The question问题

How do I generate a random long long instead of an int , with the Min and Max parameters also being long long s instead of int s?如何生成随机long long而不是intMinMax参数也是long long s 而不是int s?

The context上下文

I'm creating a deterministic game (peer-to-peer architecture), and the large minimum-size of a long long is needed as a sort of fixed-point number (since float s can cause non-determinism).我正在创建一个确定性游戏(点对点架构),并且需要long long的大最小尺寸作为一种定点数(因为float s 可能导致不确定性)。

I won't accept answers that:我不会接受以下答案:

  • Use float s or double s使用floatdouble
  • Suggest generating an int and casting it to a long long建议生成一个int并将其转换为long long
  • Generate random numbers non-deterministically (ie mersenne is deterministic if the same seed is used)非确定性地生成随机数(即,如果使用相同的种子,则梅森是确定性的)

I would much prefer a solution from the standard library if there is one.如果有标准库中的解决方案,我会更喜欢它。

Ideally, the solution should be at least as efficient as my existing code on a 64-bit machine.理想情况下,该解决方案至少应该与我在 64 位机器上的现有代码一样高效。

the documentation says that the template parameter can be long long 文档说模板参数可以long long

long long Min = 3;
long long Max = 6;
std::uniform_int_distribution<long long> Distribution(Min, Max-1);

long long Result = Distribution(Mersenne);

Would that work for you?这对你有用吗?

#include <climits>
#include <random>
#include <iostream>

int main()
{
    std::random_device rd;
    std::mt19937 gen(rd()); // Here you can use any seed to make it deterministic
    std::uniform_int_distribution<long long> distrib(LLONG_MIN, LLONG_MAX);
    
    for (int n = 0; n < 5; ++n)
        std::cout << distrib(gen) << ' ';
    
    std::cout << '\n';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM