English 中文(简体)
利用Meersenne Twister算法,C++号动力在0到1之间产生同样的随机数字?
原标题:boost c++ is generating the same random number between 0 and 1, using the Mersenne Twister algorithm?

I m 试图在0到1之间随机生成真实数字,使用Boost C++uniform_01功能和Mersenne Twister算法。 这是我的法典:

double random01(mt19937 & generator)
{
    uniform_01<mt19937> dist(generator);
    return dist();
}

int main()
{
    mt19937 generator(time(0));
    for (int i = 0; i < 10; i++) {
        cout << random01(generator) << endl;
    }
    return 0;
}

However, this code generates the same random number on every iteration of the loop. I know this is a repeat of this question, but that question was closed for being ambiguous, so I rephrased it.

最佳回答

这并不是你如何利用分配。 更类似:

#include <random>
#define abusing using

abusing namespace std;

double random01(mt19937 & engine)
{
  uniform_real_distribution<double> u01; // same as u01(0.0, 1.0); see Note below
  return u01(engine);
}

int main()
{
  // as before
}

如你所看到的那样,分配目标独立于其他一切,因此事实上,你可能希望把它变成一个全球性的,或也许是一个静态变量。

(Note that uniform_01 didn t make it into the final standard, but instead uniform_real_distribution s default constructor defaults to the interval [0, 1]. For the old Boost class you can use the analogous approach.)

问题回答

Create the uniform_01 outside the function. You need to work on the same instance to get consecutive numbers. Alternatively you can make that static.





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签