1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
class NormalDistribution implements Law {
double mu,sigma,normalizer;
public NormalDistribution(double mu, double sigma) {
this.mu=mu; this.sigma=sigma;
this.normalizer = sigma*Math.sqrt(2*Math.PI);
}
public double proba(double x) {
double t = (x-mu);
return Math.exp(-(t*t)/(2*sigma*sigma)) / normalizer;
}
}
static Random random = new Random(0);
static double gaussianSample(double mu, double sigma) {
return (random.nextGaussian())*sigma + mu;
}
public static void main(String[] args) {
int N=1000;
double[] x = new double[N];
// generate random values according to the laws
for(int i=0;i<N;i++) {
double r = (double)i/N;
// 50% of laws[0], 35% of laws[1], 15% of laws[2]
int l = (r<0.50)?0:(r<0.85)?1:2;
switch(l) {
case 0 : x[i]=gaussianSample(3.0, 1.0); break;
case 1 : x[i]=gaussianSample(5.0, 2.0); break;
case 2 : x[i]=gaussianSample(10.0, 3.0); break;
}
}
// Compute mixture coefs for the 3 following distributions
Law[] laws = new Law[3];
laws[0] = new NormalDistribution(3.0,1.0);
laws[1] = new NormalDistribution(5.0,2.0);
laws[2] = new NormalDistribution(10.0,3.0);
double[] coefs = mixtureCoefficients(x,laws);
System.out.println(Arrays.toString(coefs));
// result is [0.5034928298008519, 0.33363317002051407, 0.16287400017863374]
} |
Partager