且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

rand()函数不产生足够的随机

更新时间:2023-02-26 19:19:17

在这个函数中没有任何业务:

This has no business being in this function:

srand(time(0));

这应该在程序开始时被一次地方就在 main());和绝大多数肯定不在你的显示程序。一旦种子设置,你不应该为你的过程再做,除非你想重复一个先前的序列(它的外观,你不)。

This should be called once at the beginning of your program (a good place is just inside main()); and most-certainly not in your display routine. Once the seed is set, you should never do it again for your process unless you want to repeat a prior sequence (which by the looks of it, you don't).

也就是说,我强烈建议使用 <随机> 与C ++ 11标准库一起提供。使用它,您可以建立分布(例如: uniform_int_distribution<> ),这将为你做你的大部分模数工作,并正确地解决了这样的事情可能遇到的问题(Andon指出一个关于基于模数的某些数字的可能性)。

That said, I would strongly advise using the functionality in <random> that comes with your C++11 standard library. With it you can establish distributions (ex: uniform_int_distribution<>) that will do much of your modulo work for you, and correctly account for the problems such things can encounter (Andon pointed out one regarding likeliness of certain numbers based on the modulus).

花费一些时间与< random> 。这很值得。使用您使用的三个范围的示例:

Spend some time with <random>. Its worth it. An example that uses the three ranges you're using:

#include <iostream>
#include <random>
using namespace std;

int main()
{
    std::random_device rd;
    std::default_random_engine rng(rd());

    // our distributions.        
    std::uniform_int_distribution<> dist1(50,60);
    std::uniform_int_distribution<> dist2(200,300);
    std::uniform_int_distribution<> dist3(0,100);

    for (int i=0;i<10;++i)
        std::cout << dist1(rng) << ',' << dist2(rng) << ',' << dist3(rng) << std::endl;

    return EXIT_SUCCESS;
}

输出 >

Output (obviously varies).

58,292,70
56,233,41
57,273,98
52,204,8
50,284,43
51,292,48
53,220,42
54,281,64
50,290,51
53,220,7

是的,真的只是这么简单。像我说的,那个图书馆是这只猫的睡衣。有许多更多的东西,包括随机正态分布,不同的引擎后端等。我强烈建议您检查它。

Yeah, it really is just that simple. Like I said, that library is this cat's pajamas. There are many more things it offers, including random normal distributions, different engine backends, etc. I highly encourage you to check into it.