Поделиться через


Класс piecewise_linear_distribution

Формирует кусочно-линейное распределение с меняющимися интервалами ширины и линейно меняющейся вероятностью в каждом интервале.

Синтаксис

template<class RealType = double>
class piecewise_linear_distribution
   {
public:
   // types
   typedef RealType result_type;
   struct param_type;

   // constructor and reset functions
   piecewise_linear_distribution();
   template <class InputIteratorI, class InputIteratorW>
   piecewise_linear_distribution(
      InputIteratorI firstI, InputIteratorI lastI, InputIteratorW firstW);
   template <class UnaryOperation>
   piecewise_linear_distribution(
      initializer_list<result_type> intervals, UnaryOperation weightfunc);
   template <class UnaryOperation>
   piecewise_linear_distribution(
      size_t count, result_type xmin, result_type xmax, UnaryOperation weightfunc);
   explicit piecewise_linear_distribution(const param_type& parm);
   void reset();

   // generating functions
   template <class URNG>
   result_type operator()(URNG& gen);
   template <class URNG>
   result_type operator()(URNG& gen, const param_type& parm);

   // property functions
   vector<result_type> intervals() const;
   vector<result_type> densities() const;
   param_type param() const;
   void param(const param_type& parm);
   result_type min() const;
   result_type max() const;
   };

Параметры

RealType
По умолчанию тип результата с плавающей запятой имеет тип double. Сведения о возможных типах см <. в случайном> порядке.

Замечания

Выборочное распределение использует меняющиеся интервалы ширины с линейно меняющейся вероятностью в каждом интервале. Сведения о других выборочных распределениях см. в разделах piecewise_linear_distribution и discrete_distribution.

В следующей таблице представлены ссылки на статьи об отдельных членах.

piecewise_linear_distribution
param_type

Функция свойства intervals() возвращает значение типа vector<result_type> с набором хранимых интервалов распределения.

Функция свойства densities() возвращает значение типа vector<result_type> с хранимыми плотностями для каждого набора интервалов, которые вычисляются в соответствии с весами, заданными в параметрах конструктора.

Член свойства param() устанавливает или возвращает хранимый пакет параметров распределения param_type.

Функции-члены min() и max() возвращают наименьший и наибольший из возможных результатов соответственно.

Функция-член reset() удаляет любые кэшированные значения, чтобы результат следующего вызова operator() не зависел от любых значений, полученных от механизма перед вызовом.

Функции-члены operator() возвращают следующее значение, созданное механизмом РГСЧ, из текущего или указанного пакета параметров.

Дополнительные сведения о классах распространения и их членах см. в случайном порядке>.<

Пример

// compile with: /EHsc /W4
#include <random>
#include <iostream>
#include <iomanip>
#include <string>
#include <map>

using namespace std;

void test(const int s) {

    // uncomment to use a non-deterministic generator
    // random_device rd;
    // mt19937 gen(rd());
    mt19937 gen(1701);

    // Three intervals, non-uniform: 0 to 1, 1 to 6, and 6 to 15
    vector<double> intervals{ 0, 1, 6, 15 };
    // weights determine the densities used by the distribution
    vector<double> weights{ 1, 5, 5, 10 };

    piecewise_linear_distribution<double> distr(intervals.begin(), intervals.end(), weights.begin());

    cout << endl;
    cout << "min() == " << distr.min() << endl;
    cout << "max() == " << distr.max() << endl;
    cout << "intervals (index: interval):" << endl;
    vector<double> i = distr.intervals();
    int counter = 0;
    for (const auto& n : i) {
        cout << fixed << setw(11) << counter << ": " << setw(14) << setprecision(10) << n << endl;
        ++counter;
    }
    cout << endl;
    cout << "densities (index: density):" << endl;
    vector<double> d = distr.densities();
    counter = 0;
    for (const auto& n : d) {
        cout << fixed << setw(11) << counter << ": " << setw(14) << setprecision(10) << n << endl;
        ++counter;
    }
    cout << endl;

    // generate the distribution as a histogram
    map<int, int> histogram;
    for (int i = 0; i < s; ++i) {
        ++histogram[distr(gen)];
    }

    // print results
    cout << "Distribution for " << s << " samples:" << endl;
    for (const auto& elem : histogram) {
        cout << setw(5) << elem.first << '-' << elem.first + 1 << ' ' << string(elem.second, ':') << endl;
    }
    cout << endl;
}

int main()
{
    int samples = 100;

    cout << "Use CTRL-Z to bypass data entry and run using default values." << endl;
    cout << "Enter an integer value for the sample count: ";
    cin >> samples;

    test(samples);
}
Use CTRL-Z to bypass data entry and run using default values.
Enter an integer value for the sample count: 100
min() == 0
max() == 15
intervals (index: interval):
          0:   0.0000000000
          1:   1.0000000000
          2:   6.0000000000
          3:  15.0000000000
densities (index: density):
          0:   0.0645161290
          1:   0.3225806452
          2:   0.3225806452
          3:   0.6451612903
Distribution for 100 samples:
    0-1 :::::::::::::::::::::
    1-2 ::::::
    2-3 :::
    3-4 :::::::
    4-5 ::::::
    5-6 ::::::
    6-7 :::::
    7-8 ::::::::::
    8-9 ::::::::::
    9-10 ::::::
   10-11 ::::
   11-12 :::
   12-13 :::
   13-14 :::::
   14-15 :::::

Требования

Заголовок:<random>

Пространство имен: std

piecewise_linear_distribution::piecewise_linear_distribution

Формирует распределение.

// default constructor
piecewise_linear_distribution();

// constructs using a range of intervals, [firstI, lastI), with
// matching weights starting at firstW
template <class InputIteratorI, class InputIteratorW>
piecewise_linear_distribution(InputIteratorI firstI, InputIteratorI lastI, InputIteratorW firstW);

// constructs using an initializer list for range of intervals,
// with weights generated by function weightfunc
template <class UnaryOperation>
piecewise_linear_distribution(initializer_list<RealType>
intervals, UnaryOperation weightfunc);

// constructs using an initializer list for range of count intervals,
// distributed uniformly over [xmin,xmax] with weights generated by function weightfunc
template <class UnaryOperation>
piecewise_linear_distribution(size_t count, RealType xmin, RealType xmax, UnaryOperation weightfunc);

// constructs from an existing param_type structure
explicit piecewise_linear_distribution(const param_type& parm);

Параметры

firstI
Итератор ввода первого элемента в диапазоне распределения.

lastI
Итератор ввода последнего элемента в диапазоне распределения.

firstW
Итератор ввода первого элемента в диапазоне весов.

intervals
Объект initializer_list с интервалами распределения.

count
Количество элементов в диапазоне распределения.

xmin
Минимальное значение в диапазоне распределения.

xmax
Максимальное значение в диапазоне распределения. Должно быть больше, чем xmin.

weightfunc
Объект, представляющий функцию вероятности распределения. Параметр и возвращаемое значение должны поддерживать преобразование в тип double.

parm
Структура параметров, используемая для формирования распределения.

Замечания

Конструктор по умолчанию задает хранимые параметры таким образом, чтобы существовал один интервал от 0 до 1 с плотностью вероятности 1.

Конструктор диапазона итератора

template <class InputIteratorI, class InputIteratorW>
piecewise_linear_distribution(
    InputIteratorI firstI,
    InputIteratorI lastI,
    InputIteratorW firstW);

создает объект распределения с итералями из итераторов по последовательности [ firstI, lastI) и соответствующую последовательность весов, начиная с первогоW.

Конструктор списка инициализаторов

template <class UnaryOperation>
piecewise_linear_distribution(
    initializer_list<result_type> intervals,
    UnaryOperation weightfunc);

создает объект распределения с интервалами от интервалов списка и весов , создаваемых функцией weightfunc.

Конструктор, определенный как

template <class UnaryOperation>
piecewise_linear_distribution(
    size_t count,
    result_type xmin,
    result_type xmax,
    UnaryOperation weightfunc);

создает объект распределения с интервалами счетчика, распределенными равномерно по [xmin,xmax], присваивая каждому интервалу вес в соответствии с функцией weightfunc, и weightfunc должен принимать один параметр и иметь возвращаемое значение, оба из которых преобразуются doubleв . Предварительные условияxmin < xmax

Конструктор, определенный как

explicit piecewise_linear_distribution(const param_type& parm);

создает объект распространения с помощью parm в качестве структуры хранимых параметров.

piecewise_linear_distribution::param_type

Сохраняет все параметры распределения.

struct param_type {
   typedef piecewise_linear_distribution<result_type> distribution_type;
   param_type();
   template <class IterI, class IterW>
   param_type(
      IterI firstI, IterI lastI, IterW firstW);
   template <class UnaryOperation>
   param_type(
      size_t count, result_type xmin, result_type xmax, UnaryOperation weightfunc);
   std::vector<result_type> densities() const;
   std::vector<result_type> intervals() const;

   bool operator==(const param_type& right) const;
   bool operator!=(const param_type& right) const;
   };

Параметры

См. параметры конструктора piecewise_linear_distribution.

Замечания

Предусловие:xmin < xmax

Эту структуру можно передать конструктору класса распределения во время создания экземпляра, функции-члену param() для установки хранимых параметров существующего распределения и operator() для использования вместо хранимых параметров.

См. также

<random>