Skip to content

Instantly share code, notes, and snippets.

@evandrix
Created March 26, 2012 02:17
Show Gist options
  • Save evandrix/2202375 to your computer and use it in GitHub Desktop.
Save evandrix/2202375 to your computer and use it in GitHub Desktop.
Log Domain Computations
/*
First off, logAdd() takes two arguments of type double in log space, logX and logY.
It returns a double value which closely approximates log(X + Y). Consequently, the inputs and output are in log space, and we need not convert in and out of log space to complete this operation.
*/
public static double logAdd(double logX, double logY) {
// 1. make X the max
if (logY > logX) {
double temp = logX;
logX = logY;
logY = temp;
}
// 2. now X is bigger
if (logX == Double.NEGATIVE_INFINITY) {
return logX;
}
// 3. how far "down" (think decibels) is logY from logX?
// if it's really small (20 orders of magnitude smaller), then ignore
double negDiff = logY - logX;
if (negDiff < -20) {
return logX;
}
// 4. otherwise use some nice algebra to stay in the log domain
// (except for negDiff)
return logX + java.lang.Math.log(1.0 + java.lang.Math.exp(negDiff));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment