如何在 c/c++ 中顺序创建伪随机数?

发布于 2024-11-02 06:25:23 字数 173 浏览 14 评论 0原文

srand(time(NULL));
for (it=hand.begin(); it < hand.end(); it++)
    (*it) = rand() % 13 + 1;

此代码无法一次创建许多随机数。 有没有一种方法可以不像梅森那么复杂并且不依赖于操作系统?

srand(time(NULL));
for (it=hand.begin(); it < hand.end(); it++)
    (*it) = rand() % 13 + 1;

This code does not work to create many random numbers at a time.
Is there a way to do it that isn't as complex as Mersennes and isn't operating system dependent?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

っ左 2024-11-09 06:25:23

PRNG 不会同时创建许多 PRN。每个输出都依赖于前一个输出,PRNG 具有高度状态性。

尝试:

srand(time(NULL)); // once at the start of the program

for( int i = 0; i < N; ++i )
    r[i] = rand();

即使 API 在单个函数调用中返回整个输出块,也只是将该循环移至函数内部。

PRNGs don't create many PRNs at once. Each output is dependent on the previous output, PRNGs are highly stateful.

Try:

srand(time(NULL)); // once at the start of the program

for( int i = 0; i < N; ++i )
    r[i] = rand();

Even APIs that return an entire block of output in a single function call, have just moved that loop inside the function.

蓝海 2024-11-09 06:25:23

在程序开始时仅调用 srand 一次。然后调用rand()不是srand(rand()))来生成每个随机数。

Call srand just once, at the start of your program. Then call rand() (not srand(rand())) to generate each random number.

神经大条 2024-11-09 06:25:23

Boost.Random 有很多很好的随机数生成器,易于使用。

Boost.Random has lots of good random number generators which are easy to use.

江心雾 2024-11-09 06:25:23

George Marsaglia 不久前在 sci.math 中发布了乘以进位 PRNG

我不能说它有多好或者它的表现有多好,但你可能想尝试一下。

它应该独立于操作系统和平台。

George Marsaglia posted a Multiply With Carry PRNG some time ago in sci.math.

I cannot say how good it is or how well it behaves, but you might want to give it a try.

It should be OS and platform independent.

陪你搞怪i 2024-11-09 06:25:23

“请确保你回答了问题”
好吧,

for (int i=n1; i < n2; ++i)
  { 
  int k; 
  do k = rand(); while (i !=k); 
  // k is a sequential pseudo random number
  }

效率可能有问题......

"please make sure you answer the question"
OK

for (int i=n1; i < n2; ++i)
  { 
  int k; 
  do k = rand(); while (i !=k); 
  // k is a sequential pseudo random number
  }

There may be issues with efficiency...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文