[ create a new paste ] login | about

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

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

using namespace std;
using namespace boost;

class Kernel {
private:
  double X;

public:
  Kernel(double x) : X(x) {}
  double density(double x, double h) const { 
    return exp(-pow((x-X) / h, 2) / 2) / sqrt(2 * M_PI);
  }
};

double sum_of_kernel_density(const vector<Kernel> &k, double x, double h) {
  double sum = 0;
  for (int i = 0; i < (int)k.size(); ++i) {
    sum += k[i].density(x, h); 
  }
  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<Kernel> k;
  for(int i = 0; i < N; ++i) {
    k.push_back(Kernel(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: