【问题标题】:more diversity in randomizing numbers?随机数字的更多多样性?
【发布时间】:2022-01-10 03:20:52
【问题描述】:

我正在制作一个赛马游戏。 我每 500 毫秒显示一次赛道,并为每匹马添加 1-4 之间的随机位置,但似乎几乎每次 5 胜,它就像 70%。

在另一个名为轮盘赌的游戏上也是如此,平均被选中的数字是 11。

我正在使用 Mersenne Twister 生成器,这是我正在使用的方法:

int random(int a, int b)  {
    static std::random_device rd;
    static std::mt19937 generator(rd());
    std::uniform_real_distribution<> distribution( a, b );
    return distribution(generator);
}

关于使数字更加随机的任何提示?

【问题讨论】:

标签: c++ random numbers


【解决方案1】:

正如理查德所说,只要 a 和 b 不变,您就需要保留分布的实例。所以最好将该状态包装在一个类中,之后数字的分布就可以了。这是下面示例中 100000 个数字的输出。

value : 1, occured 24911 times
value : 2, occured 25044 times
value : 3, occured 25012 times
value : 4, occured 25033 times

#include <array>
#include <random>
#include <iostream>

// wrap your number generation in a helper class so it can maintain state.
class random_t
{
public:
    // initialize generator and distribution
    random_t(const int min, const int max) :
        m_generator{ std::random_device{}() },
        m_distribution{ min,max }
    {
    }

    // get next random number
    int operator()()
    {
        return m_distribution(m_generator);
    }

private:
    std::mt19937 m_generator;
    std::uniform_int_distribution<int> m_distribution;
};

// run random generator and create a histogram
int main()
{
    random_t random(1, 4);
    std::array<int, 5> histogram{};

    for (std::size_t n = 0; n < 100000; ++n)
    {
        auto value = random();
        //std::cout << value << " ";
        histogram[value]++;
    }

    for (std::size_t n = 1; n < 5; ++n )
    {
        std::cout << "value : " << n << ", occured " << histogram[n] << " times\n";
    }

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 2023-04-11
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    相关资源
    最近更新 更多