diff src/samer/maths/random/PosteriorSampler.java @ 0:bf79fb79ee13

Initial Mercurial check in.
author samer
date Tue, 17 Jan 2012 17:50:20 +0000
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/samer/maths/random/PosteriorSampler.java	Tue Jan 17 17:50:20 2012 +0000
@@ -0,0 +1,50 @@
+package samer.maths.random;
+import samer.maths.*;
+import samer.core.*;
+
+/**
+ sample from posterior
+ instead of supplying weighting factor,
+ reject a fraction of the samples 
+ make take a long time if A<<sigma
+*/
+
+class PosteriorSampler extends BaseRandom
+{
+	double A, sigma;
+	double std, var, mean;
+
+	public PosteriorSampler() {}
+
+	public void setA(double a) { A=a; std=sigma/A; var=std*std; }
+	public void setSigma(double s) { sigma=s; std=sigma/A; var=std*std; }
+	public void setx(double x) { mean=x/A; }
+
+	public double next() 
+	{
+		double v;
+		boolean ok=false;
+
+		do {
+			v=mean + std*rnd.nextGaussian();
+
+			if (v<=-var) {
+				v=v+var;
+				if (mean<0) {
+					double k=Math.exp(2*mean);
+					double u=rnd.nextDouble();
+					if (u<k) ok=true;
+				} else ok=true;
+			} else if (v>=var) {
+				v=v-var;
+				if (mean>0) {
+					double k=Math.exp(-2*mean);
+					double u=rnd.nextDouble();
+					if (u<k) ok=true;
+				} else ok=true;
+			}
+		} while (!ok);
+
+		return v;
+	}
+}