在c+中是否有使用三角形分布生成随机数的函数+;? < >我在C++中搜索函数,我给它(min,模式,max),然后返回由三角形分布生成的随机数。如果有实现此功能的代码,它将非常好。
可用于模拟三角形分布 下面是一个基于链接参考页上的示例代码的示例,该示例生成一个三角形分布,该分布生成0到30之间的数字,峰值为20:在c+中是否有使用三角形分布生成随机数的函数+;? < >我在C++中搜索函数,我给它(min,模式,max),然后返回由三角形分布生成的随机数。如果有实现此功能的代码,它将非常好。,c++,simulation,distribution,C++,Simulation,Distribution,可用于模拟三角形分布 下面是一个基于链接参考页上的示例代码的示例,该示例生成一个三角形分布,该分布生成0到30之间的数字,峰值为20: #include <random> #include <iostream> #include <iomanip> #include <array> #include <map> std::piecewise_linear_distribution<double> triangular_di
#include <random>
#include <iostream>
#include <iomanip>
#include <array>
#include <map>
std::piecewise_linear_distribution<double> triangular_distribution(double min, double peak, double max)
{
std::array<double, 3> i{min, peak, max};
std::array<double, 3> w{0, 1, 0};
return std::piecewise_linear_distribution<double>{i.begin(), i.end(), w.begin()};
}
int main() {
std::random_device rd;
// create a mersenne twister PRNG seeded from some implementation-defined random source
std::mt19937 gen(rd());
// create a triangular distribution with a minimum of 0, a peak at 20, and a maximum of 30
auto dist = triangular_distribution(0, 20, 30);
std::map<int, int> hist;
// use our distribution to generate 10,000 random numbers
// (truncated to integers for the sake of output; the generated numbers are actually real numbers)
for (int i = 0; i < 10000; ++i) {
double num = dist(gen);
++hist[num];
}
// print out a nice histogram of the numbers generated
for(auto p : hist) {
std::cout << std::setw(2) << std::setfill('0') << p.first << ' '
<< std::string(p.second/10,'*') << '\n';
}
}
你可以从一个简单的三角形分布T中取样,将两个均匀分布U求和₁ 和你₂. 在C方面,这将是:
float U1 = (float)rand() / RAND_MAX;
float U2 = (float)rand() / RAND_MAX;
float T = U1 + U2;
相应缩放:结果在0和2之间,模式为1。也许可以做您需要的事情?谢谢。但是我怎样才能使用它呢@你说的R函数是什么意思?您指的是
R
语言吗?您是否要求在C++
中使用类似于R
中可用函数的函数?@JosephWood否我使用R作为函数名。
float U1 = (float)rand() / RAND_MAX;
float U2 = (float)rand() / RAND_MAX;
float T = U1 + U2;