[ create a new paste ] login | about

Link: http://codepad.org/Th2GPFrW    [ raw code | output | fork ]

C++, pasted on Dec 18:
#include <iostream>
#include <vector>
#include <cmath>
#include <boost/shared_ptr.hpp>
#include <boost/random.hpp>

using namespace std;
using namespace boost;

double sum_of_kernel_density(const vector<double> &k, double x, double h) {                             
  double sum = 0;                                                                                       
  for (int i = 0; i < (int)k.size(); ++i) {                                                             
    sum += exp(-pow((x-k[i]) / h, 2) / 2) / sqrt(2 * M_PI);                                             
  }
  return sum / (k.size() * h);
}

int main() {                                                                                            
  const unsigned int seed = 123;                                                                        
  mt19937 gen(seed);
  normal_distribution<double> dst(5.0, 1.0);                                                            
  variate_generator<mt19937, normal_distribution<double> > r_norm(gen, dst);                            

  const int N = 100;
  vector<double> k;
  for(int i = 0; i < N; ++i) {
    k.push_back(r_norm());
  }

  const double h = 0.7;
  for(int i = 0; i < 10; ++i) {                                                                         
    cout << i << "\t" << sum_of_kernel_density(k, i, h) << endl;                                        
  }
  return 0; 
}


Output:
1
2
3
4
5
6
7
8
9
10
0	2.72898e-07
1	0.000121768
2	0.00827342
3	0.100135
4	0.290664
5	0.319885
6	0.203549
7	0.064411
8	0.0112637
9	0.00164454


Create a new paste based on this one


Comments: