случайный заголовок | Набор 2 (Распределения)
Опубликовано: 5 Января, 2022
Набор 1 (Генераторы)
Распределения
I. Униформа:
- uniform_int_distribution: производит случайные целочисленные значения i, которые равномерно распределяются на закрытом интервале [a, b], который описывается следующей функцией массы вероятности:
- operator (): он генерирует случайные числа, которые распределяются в соответствии с функцией вероятности.
- min: возвращает наибольшую нижнюю границу диапазона значений, возвращаемых operator (), который является параметром распределения 'a' для uniform_int_distribution.
- max: возвращает наименьшую верхнюю границу диапазона значений, возвращаемых operator (), который является параметром распределения 'b' для uniform_int_distribution.
- reset: сбрасывает распределение, так что при последующих использованиях результат не зависит от уже созданных им значений.
// C++ program to illustrate
// the use of operator()
// in uniform_int_distribution
#include <iostream>
#include <random>
using
namespace
std;
// Driver program
int
main()
{
// Constructing a trivial random generator engine
unsigned s = 2;
// The random number generator
default_random_engine generator (s);
uniform_int_distribution<
int
> distribution(1,10);
cout <<
"Some random numbers between 1 and 10"
;
for
(
int
i = 0; i < 10; ++i)
cout << distribution(generator) ;
cout << endl;
return
0;
}
Выход:
Некоторые случайные числа от 1 до 10: 1 3 6 10 1 5 1 4 4 9
// C++ program to illustrate
// the use of reset
// in uniform_int_distribution
#include <iostream>
#include <random>
using
namespace
std;
//Driver program
int
main()
{
//the random number generator
default_random_engine generator;
// Initialising the uniform distribution
uniform_int_distribution<
int
> distribution(1, 1000);
// First random number is generated
cout << distribution(generator) << endl;
//Resets the distribution
distribution.reset();
// Second random number is
//generated independent of previous number
cout << distribution(generator) << endl;
return
0;
}
Выход:
1 132
- uniform_real_distribution: это распределение случайных чисел, которое производит значения с плавающей запятой, которое описывается следующей функцией плотности вероятности:
- operator (): возвращает новое случайное число, соответствующее параметрам распределения.
- min: возвращает наибольшую нижнюю границу диапазона значений, возвращаемых operator (), который является параметром распределения 'a' для uniform_real_distribution.
- max: возвращает наименьшую верхнюю границу диапазона значений, возвращаемых operator (), который является параметром распределения 'b' для uniform_real_distribution.
- reset: сбрасывает распределение, так что при последующих использованиях результат не зависит от уже созданных им значений.
// C++ program to illustrate
// the use of operator()
// in uniform_int_distribution
#include <iostream>
#include <random>
using
namespace
std;
// Driver program
int
main()
{
// Constructing a trivial random generator engine
unsigned s = 2;
// The random number generator
default_random_engine generator (s);
uniform_int_distribution<
int
> distribution(1,10);
cout <<
"Random numbers between 1 and 10"
;
for
(
int
i = 0; i< 10; ++i)
cout << distribution(generator) ;
cout << endl;
return
0;
}
Выход:
некоторые случайные числа от 0,0 до 10,0: 0,150031 9,77072 3,36669 7,06447 5,11455 8,43061 1,93792 7,78965 8,31532 5,14354
// C++ program to illustrate
// the use of reset
// in uniform_real_distribution
#include <iostream>
#include <random>
using
namespace
std;
// Driver program
int
main()
{
default_random_engine generator;
uniform_real_distribution<
double
> distribution(0.0,100.0);
// It prints two independent values:
// First random number is generated
cout << distribution(generator) << endl;
//Resets the distribution
distribution.reset();
// Second random number is
//generated independent of previous number
cout << distribution(generator) << endl;
return
0;
}
Выход:
13,1538 45 865
II. Относительно испытаний Бернулли:
- bernoulli_distribution: это распределение случайных чисел, которое производит булевские значения в соответствии с распределением Бернулли, заданным следующей функцией массы вероятности:
- operator (): возвращает новое случайное число.
- min: возвращает наибольшую нижнюю границу диапазона значений, возвращаемых operator (), что для bernoulli_distribution является ложным.
- max: возвращает наименьшую верхнюю границу диапазона значений, возвращаемых operator (), что для bernoulli_distribution истинно.
// C++ program to illustrate
// the bernoulli_distribution
#include <iostream>
#include <random>
using
namespace
std;
//Driver program
int
main()
{
const
int
temp=500;
//The random number generator
default_random_engine generator;
//Initialising the bernoulli distribution
bernoulli_distribution distribution(0.7);
// count number of trues
int
count=0;
for
(
int
i = 0; i < temp; ++i)
{
// checking for true condition
if
(distribution(generator))
count++;
}
cout <<
"bernoulli_distribution (0.7) x 500:"
<< endl;
cout <<
"true: "
<< count << endl;
cout <<
"false: "
<< temp-count << endl;
return
0;
}
Выход:
bernoulli_distribution (0,7) x 500: правда: 360 ложь: 140
// C++ program to
// illustrate the use of reset
#include <iostream>
#include <random>
using
namespace
std;
//Driver program
int
main()
{
// Random number generator
default_random_engine generator;
// Initialising the bernoulli distribution
bernoulli_distribution distribution;
// print two independent values:
cout << distribution(generator) << endl;
// use of reset
// Generates second output without
// the effect of first output
distribution.reset();
cout << distribution(generator) << endl;
return
0;
}
Выход:
1 1
- binomial_distribution: это распределение случайных чисел, которое производит целые числа в соответствии с биномиальным дискретным распределением, которое задается этой функцией массы вероятности:
- operator (): генерирует новое случайное число.
- max: возвращает наименьшую верхнюю границу диапазона, заданного оператором (), который для binomial_distribution является параметром распределения t.
- min: возвращает наибольшую нижнюю границу диапазона, заданного элементом operator (), который для binomial_distribution всегда равен нулю.
- reset: сбрасывает распределение, так что последующее использование объекта не зависит от уже созданных им значений.
// C++ program to illustrate
// the use of binomial_distribution
#include <iostream>
#include <chrono>
#include <random>
using
namespace
std;
int
main()
{
// construct a trivial random
//generator engine from a time-based seed:
unsigned seed = chrono::system_clock::now().time_since_epoch().count();
default_random_engine generator (seed);
// Initialising binomial distribution
binomial_distribution<
int
> distribution (15, 0.4);
cout <<
"some binomial results (t=15, p=0.4): "
;
for
(
int
i = 0; i < 15; ++i)
{
// Use of operator()
cout << distribution(generator) <<
" "
;
}
cout << endl;
return
0;
}
Выход:
некоторые биномиальные результаты (t = 15, p = 0,4): 7 6 7 8 4 6 7 6 9 3 5 6 4 6 7
// C++ program to illustrate
// the use of binomial_distribution
#include <iostream>
#include <chrono>
#include <random>
using
namespace
std;
int
main()
{
// construct a trivial random
//generator engine from a time-based seed:
unsigned seed = chrono::system_clock::now().time_since_epoch().count();
default_random_engine generator (seed);
// Initialising binomial distribution
binomial_distribution<
int
> distribution (15, 0.4);
cout <<
"some binomial results (t=15, p=0.4): "
;
for
(
int
i = 0; i < 15; ++i)
{
// Use of operator()
cout << distribution(generator) <<
" "
;
}
cout << endl;
return
0;
}
Выход:
57 год 52
- геометрическое_распределение: это распределение случайных чисел, которое производит целые числа в соответствии с геометрическим дискретным распределением, задаваемым следующей функцией вероятности-массы:
- operator (): возвращает новое случайное число, соответствующее параметрам распределения.
- max: возвращает наименьшую верхнюю границу диапазона, заданного оператором ().
- min: возвращает минимальное значение, заданное оператором ().
- reset: сбрасывает распределение, так что последующее использование объекта не зависит от уже созданных им значений.
// C++ program to illustrate
//the use of geometric_distribution
#include <iostream>
#include <chrono>
#include <string>
#include <random>
using
namespace
std;
int
main()
{
// construct a trivial random
// generator engine from a time-based seed:
int
seed = chrono::system_clock::now().time_since_epoch().count();
default_random_engine generator (seed);
// Initialises the geometric distribution
geometric_distribution<
int
> distribution (1.0 / 5);
cout <<
"Plus sign is 5 spaces away from the next :"
<< endl;
for
(
int
i = 0; i < 10 ; ++i)
{
int
number = distribution(generator);
cout << string (number,
' '
) <<
"+"
;
}
return
0;
}
Выход:
каждый знак плюс находится на расстоянии 5 делений от следующего: ++ + + + ++ + ++
// C++ program to illustrate
// the use of reset
#include <iostream>
#include <random>
using
namespace
std;
// Driver program
int
main()
{
// Random number generator
default_random_engine generator;
// Initialising the geometric distribution
geometric_distribution<
int
> distribution(0.3);
// Prints two independent values:
// Generates the first value
cout << distribution(generator) << endl;
// Use of reset
distribution.reset();
// Generates second value
cout << distribution(generator) << endl;
return
0;
}
Выход:
0 1
- negative_binomial_distribution: это распределение случайных чисел, которое производит целые числа в соответствии с отрицательным биномиальным дискретным распределением (также известным как распределение Паскаля), заданным следующей функцией вероятности и массы:
- operator (): возвращает новое случайное число, которое следует параметрам распределения.
- max: возвращает наименьшую верхнюю границу диапазона, заданного оператором ().
- min: возвращает минимальное значение, заданное operator (), которое для negative_binomial_distribution всегда равно нулю.
- reset: сбрасывает распределение, так что последующее использование объекта не зависит от уже созданных им значений.
// C++ program to illustrate
// the use of operator() in
// negative_binomial_distribution
#include <iostream>
#include <chrono>
#include <random>
using
namespace
std;
// Driver program
int
main()
{
// construct a trivial random
// generator engine from a time-based seed:
unsigned seed = chrono::system_clock::now().time_since_epoch().count();
default_random_engine generator (seed);
// Initialising negative binomial distribution
negative_binomial_distribution<
int
> distribution (6,0.7);
cout <<
"Negative binomial results (t=6, p=0.7): "
;
for
(
int
i = 0; i < 15; ++i)
{
// Use of operator
cout << distribution(generator) <<
" "
;
}
cout << endl;
return
0;
}
Выход:
Отрицательные биномиальные результаты (t = 6, p = 0,7): 2 6 3 1 4 1 4 1 2 0 7 3 4 4 4
// C++ program to illustrate
// the use of reset in
// negative_binomial_distribution::
#include <iostream>
#include <random>
using
namespace
std;
// Driver program
int
main()
{
// Random number generator
default_random_engine generator;
// Initialising the negative binomial distribution
negative_binomial_distribution<
int
> distribution(20, 0.5);
// print two independent values:
// Generates the first value
cout << distribution(generator) << endl;
// Use of reset
distribution.reset();
// Generates the second value
cout << distribution(generator) << endl;
return
0;
}
Выход:
23 30
III. По частям:
- дискретное_распределение: это распределение случайных чисел, которое производит целочисленные значения в соответствии с дискретным распределением.
- operator (): возвращает новое случайное число, соответствующее параметрам распределения.
- max: возвращает наименьшую верхнюю границу диапазона, заданного оператором ().
- min: возвращает наибольшую нижнюю границу диапазона, заданного оператором ().
- reset: сбрасывает распределение, так что последующее использование объекта не зависит от уже созданных им значений.
// C++ program to illustrate the
// use of operator() in
// discrete_distribution
#include <iostream>
#include <random>
using
namespace
std;
int
main()
{
// number of experiments
int
n = 10000;
// maximum number of stars to distribute
int
m = 100;
// Random number generator
default_random_engine generator;
//Initialising discrete distribution
discrete_distribution<
int
> distribution { 2, 2, 1, 1, 2, 2, 1, 1, 2, 2 };
int
p[10] = {};
// use of operator()
for
(
int
i = 0; i < n; i++)
{
int
number = distribution(generator);
p[number]++;
}
cout <<
"a discrete_distribution:"
<< endl;
for
(
int
i = 0; i < 10; ++i)
{
cout << i <<
": "
<< string(p[i]*m/n,
'*'
) << endl;
}
return
0;
}
Выход:
дискретное_распределение: 0: ************ 1: ************* 2: ***** 3: ****** 4: ************ 5: ************ 6: ****** 7: ****** 8: ************ 9: ************
// C++ program to illustrate
//the use of reset in
//discrete_distribution
#include <iostream>
#include <random>
using
namespace
std;
// Driver program
int
main()
{
// Random number generator
default_random_engine generator;
// Initialising the discrete distribution
discrete_distribution<
int
> distribution {20,20,30,40};
// print two independent values:
// Generates the first value
cout << distribution(generator) << endl;
// Use of reset
distribution.reset();
// Generates the secong value
cout << distribution(generator) << endl;
return
0;
}
Выход:
0 2
- piecewise_constant_distribution: это распределение случайных чисел, которое производит значени