离散到连续累积密度函数

时间:2018-06-11 16:26:39

标签: c++ class c++11 stdvector probability-density

我的问题是,是否可以转换存储原始CDF样本的矢量(累积密度函数)......

类似的东西:

class normal
{
 public:

   float mean;
   float sigma;
   float variance = sigma * sigma;
   float left_margin = mean - 4 * sigma;
   float right_margin = mean + 4 * sigma;
   normal():mean(0), sigma(1){}
   normal(float m, float s):mean(m), sigma(s){}

   float cdf(float x); 
   float pdf(float x); 
};

float normal::pdf(float x)
{
   if (x < left_margin || x > right_margin)     return 0;

   float coefficient = 1 / (float)sqrt(2 * PI * variance);

   float x_mean = x - mean;
   float result = coefficient * exp(-(x_mean * x_mean) / 2 * variance);
   return result;
}

float normal::cdf(float x) 
{
   if (x <= left_margin)      return 0;
   if (x >= right_margin)     return 1;

   float x_mean = x - mean;
   float result = (float)(0.5 * (1 + erf((x_mean) / sqrt(2 * variance))));
   if (result > 1) return 1;
   else return result;
}

std::vector<float> discrete_normal_cdf(normal& X)
{
   std::vector<float> vec;

   float L = (float)(X.left_margin);
   float R = (float)(1.2 * X.right_margin);

   while (L <= R)
   {
      vec.push_back(X.cdf(L));
      L = (float)(L + 0.1);
   }   

   std::vector<float> tmp;
   // take three samples
   tmp.push_back(vec.at(1));    // first non_zero element
   tmp.push_back(vec.at(40));   // add element with value of 0.5
   tmp.push_back(vec.at(80));   // element with value of 0.99


   std::vector<float> cdf_v(5, 0);

   for (auto i = 0; i < tmp.size(); i++)
      cdf_v.push_back(tmp.at(i));

   int l = 0;
   while (l < 5)
   {
      cdf_v.push_back(1);
      l++;
   }
   return cdf_v;
}

实际上我需要的是:如果我们有正常的

 normal n1(5, 1);

将其CDF样本分成线性CDF:

 vector<float> foo = discrete_normal_cdf(n1); 

然后将分段线性CDF重建为正常

 normal function(foo)
 {
    return normal(5, 1);
 }

此功能有效吗? 我写了一个以矢量作为输入的函数 并搜索向量的所有元素,值为0.5 并返回该元素的索引作为法线的平均值 但并非总是如此。

normal vec2normal(vector<float>& vec)
{
     int mean;
     mean = std::find(vec.begin(), vec.end(), 0.5) - vec.begin();
     return normal(mean, 1);
}

我不知道如何做到这一点,所以任何建议都将不胜感激 谢谢。

0 个答案:

没有答案