C++:生成高斯分布

发布于 2024-07-26 20:20:57 字数 83 浏览 3 评论 0原文

我想知道 C++ 标准库中是否有任何高斯分布数字生成器,或者是否有任何代码片段要传递。

提前致谢。

I would like to know if in C++ standard libraries there is any gaussian distribution number generator, or if you have any code snippet to pass.

Thanks in advance.

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

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

发布评论

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

评论(4

∞梦里开花 2024-08-02 20:20:57

标准库没有。 然而,Boost.Random 确实如此。 如果我是你我就会用它。

The standard library does not. Boost.Random does, however. I'd use that if I were you.

银河中√捞星星 2024-08-02 20:20:57

C++ 技术报告 1 添加了对随机数生成的支持。 因此,如果您使用的是相对较新的编译器(Visual C++ 2008 GCC 4.3),那么它很可能是开箱即用的。

有关 std::tr1::normal_distribution 的示例用法,请参阅此处(还有很多)。

C++ Technical Report 1 adds support for random number generation. So if you're using a relatively recent compiler (visual c++ 2008 GCC 4.3), chances are that it is available out of the box.

See here for sample usage of std::tr1::normal_distribution (and many more).

自我难过 2024-08-02 20:20:57

GNU 科学图书馆有这个功能。 GSL - 高斯分布

The GNU Scientific Libraries has this feature. GSL - Gaussian Distribution

没︽人懂的悲伤 2024-08-02 20:20:57

这个问题的答案随着 C​​++11 的变化而变化,它具有 随机标头其中包括 std::normal_distribution。 Walter Brown 的论文N3551,C++11 中的随机数生成 可能是对该库的更好介绍之一。

以下代码演示了如何使用此标头(实时查看):

#include <iostream>
#include <iomanip>
#include <map>
#include <random>

int main()
{
    std::random_device rd;

    std::mt19937 e2(rd());

    std::normal_distribution<> dist(2, 2);

    std::map<int, int> hist;
    for (int n = 0; n < 10000; ++n) {
        ++hist[std::floor(dist(e2))];
    }

    for (auto p : hist) {
        std::cout << std::fixed << std::setprecision(1) << std::setw(2)
                  << p.first << ' ' << std::string(p.second/200, '*') << '\n';
    }
}

我提供在我对 C++ 随机浮点数生成 的回答中,有一组更通用的 C++11 随机数生成示例Boost 中的示例以及使用 rand()

The answer to this question changes with C++11 which has the random header which includes std::normal_distribution. Walter Brown's paper N3551, Random Number Generation in C++11 is probably one of the better introductions to this library.

The following code demonstrates how to use this header (see it live):

#include <iostream>
#include <iomanip>
#include <map>
#include <random>

int main()
{
    std::random_device rd;

    std::mt19937 e2(rd());

    std::normal_distribution<> dist(2, 2);

    std::map<int, int> hist;
    for (int n = 0; n < 10000; ++n) {
        ++hist[std::floor(dist(e2))];
    }

    for (auto p : hist) {
        std::cout << std::fixed << std::setprecision(1) << std::setw(2)
                  << p.first << ' ' << std::string(p.second/200, '*') << '\n';
    }
}

I provide a more general set of examples to random number generation in C++11 in my answer to C++ random float number generation with an example in Boost and using rand() as well.

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