首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++随机值和Blitz++

C++随机值和Blitz++
EN

Stack Overflow用户
提问于 2015-02-03 02:33:16
回答 1查看 96关注 0票数 0

下面的代码正在编译和运行。代码应该将Blitz矩阵初始化为随机值,但它失败了,因为矩阵的每个元素都获得了相同的值。

代码语言:javascript
复制
#include <iostream>
#include <array>
#include <algorithm>
#include <functional>
#include <random>
#include <blitz/array.h>

int main()
{
    // random
    std::random_device __device;
    std::array<int, std::mt19937::state_size> __seeds;
    std::normal_distribution<double> __distribution(0.0, 1.0);
    std::mt19937 __engine;
    std::generate_n(__seeds.data(), __seeds.size(), std::ref(__device));
    std::seed_seq __sequence(std::begin(__seeds), std::end(__seeds));
    __engine.seed(__sequence);

    // matrix
    blitz::Array<float,2> a(4,5);
    a=__distribution(__engine);

    // io
    std::cout << a << std::endl;
}

输出结果不是我想要的

代码语言:javascript
复制
(0,3) x (0,4)
[ -1.10231 -1.10231 -1.10231 -1.10231 -1.10231 
  -1.10231 -1.10231 -1.10231 -1.10231 -1.10231 
  -1.10231 -1.10231 -1.10231 -1.10231 -1.10231 
  -1.10231 -1.10231 -1.10231 -1.10231 -1.10231 ]

将闪电战矩阵初始化为随机值的正确方法是什么?

EN

回答 1

Stack Overflow用户

发布于 2015-02-04 02:54:45

你说让每个单元格都是这个值,试试这个

代码语言:javascript
复制
#include <iostream>
#include <array>
#include <algorithm>
#include <functional>
#include <random>
#include <blitz/array.h>

int main()
{
    // random
    std::random_device __device;
    std::array<int, std::mt19937::state_size> __seeds;
    std::normal_distribution<double> __distribution(0.0, 1.0);
    std::mt19937 __engine;
    std::generate_n(__seeds.data(), __seeds.size(), std::ref(__device));
    std::seed_seq __sequence(std::begin(__seeds), std::end(__seeds));
    __engine.seed(__sequence);

    // matrix
    blitz::Array<float,2> a(4,5);
    for( int i=0; i<4; ++i ) {
        for( int j=0; j<5; ++j ) {
            a(i, j) =__distribution(__engine);      
        }
    }


    // io
    std::cout << a << std::endl;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28284380

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档