本文介绍了uniform_real_distribution 不均匀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我理解这一点.运行代码段后:

Please, help me understand this. After running the snippet:

random_device randomEngine;
mt19937 generatorEngine(randomEngine());
uniform_real_distribution<double> unifRandomValue(
                                       numeric_limits<double>::min(),
                                       numeric_limits<double>::max());

double test[1000];
for (int i{ 0 }; i < 1000; ++i) {
    test[i] = unifRandomValue(generatorEngine);
}

为什么每个生成的值都在 [1.0E306, 1.8E308] 范围内?我期待一个随机值从接近 0 到 double 类型的最大值均匀分布.

Why is every generated value in the range [1.0E306, 1.8E308]? I was expecting a random value uniformly distributed from near 0 to the max of double type.

提前致谢!

const size_t size{ 1000 };
std::random_device randomEngine;
std::mt19937 generatorEngine(randomEngine());
std::uniform_real_distribution<double> unifRandomValue(
                                std::numeric_limits<double>::min(),
                                std::numeric_limits<double>::max());

std::array<double, size> test;
for (int i{ 0 }; i < size; ++i) {
    test[i] = unifRandomValue(generatorEngine);
}

auto minMaxIt = std::minmax_element(test.begin(), test.end());

// average without overflow
double average{ 0.0 };
for (int i{ 0 }; i < size; ++i) {
    average += test[i] / size;
}

std::cout << "min value : " << *minMaxIt.first << std::endl;
std::cout << "max value : " << *minMaxIt.second << std::endl;
std::cout << "average   : " << average << endl;

// one possible output (they are all similar)
//  min value : 1.73361e+305
//  max value : 1.79661e+308
//  average : 8.78467e+307

推荐答案

嗯,这是统一生成器的属性:

90% 的值将处于您指定的最高数量级.

想得更小;考虑 0 到 99 之间的整数范围:90% 的图纸将有 2 位数字.

Think smaller; consider the integer range 0 to 99 inclusive: 90% of the drawings will have 2 digits.

这篇关于uniform_real_distribution 不均匀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 05:32