-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSloppyMath.java
More file actions
87 lines (76 loc) · 1.92 KB
/
Copy pathSloppyMath.java
File metadata and controls
87 lines (76 loc) · 1.92 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package com.rutgers.util;
import java.lang.*;
import java.lang.Math;
/**
* Routines for some approximate math functions.
*/
public class SloppyMath {
public static double min(int x, int y) {
if (x > y) return y;
return x;
}
public static double min(double x, double y) {
if (x > y) return y;
return x;
}
public static double max(int x, int y) {
if (x > y) return x;
return y;
}
public static double max(double x, double y) {
if (x > y) return x;
return y;
}
public static double abs(double x) {
if (x > 0)
return x;
return -1.0 * x;
}
public static double logAdd(double logX, double logY) {
// make a the max
if (logY > logX) {
double temp = logX;
logX = logY;
logY = temp;
}
// now a is bigger
if (logX == Double.NEGATIVE_INFINITY) {
return logX;
}
double negDiff = logY - logX;
if (negDiff < -20) {
return logX;
}
return logX + java.lang.Math.log(1.0 + java.lang.Math.exp(negDiff));
}
public static double logAdd(double[] logV) {
double max = Double.NEGATIVE_INFINITY;
double maxIndex = 0;
for (int i = 0; i < logV.length; i++) {
if (logV[i] > max) {
max = logV[i];
maxIndex = i;
}
}
if (max == Double.NEGATIVE_INFINITY) return Double.NEGATIVE_INFINITY;
// compute the negative difference
double threshold = max - 20;
double sumNegativeDifferences = 0.0;
for (int i = 0; i < logV.length; i++) {
if (i != maxIndex && logV[i] > threshold) {
sumNegativeDifferences += Math.exp(logV[i] - max);
}
}
if (sumNegativeDifferences > 0.0) {
return max + Math.log(1.0 + sumNegativeDifferences);
} else {
return max;
}
}
public static double exp(double logX) {
// if x is very near one, use the linear approximation
if (abs(logX) < 0.001)
return 1 + logX;
return Math.exp(logX);
}
}