From 85e89fb9a69dfd5b73b7fc3e1b213decf698335c Mon Sep 17 00:00:00 2001
From: Daniel Waggoner <dwaggoner@frbatlanta.org>
Date: Fri, 5 Aug 2011 16:22:19 -0400
Subject: [PATCH] fixed AddScaledLogs() so zero weights can be safely passed
 (cherry picked from commit fc074f98b74acb38d66dcd6e32ee0a5836e930e2)

---
 math/dw_math.c | 15 ++++++++++-----
 1 file changed, 10 insertions(+), 5 deletions(-)

diff --git a/math/dw_math.c b/math/dw_math.c
index 50b3534..288a99e 100644
--- a/math/dw_math.c
+++ b/math/dw_math.c
@@ -34,14 +34,19 @@ PRECISION AddLogs(PRECISION a, PRECISION b)
 
 /*
    Returns ln(x*exp(a) + y*exp(b)) computed to avoid overflow.  If a = ln(c) and 
-   b = ln(d), as is usually the case, then the routine returns ln(x*c + y*d).  
-   Assumes that x*exp(a) + y*exp(b) is positive, but no checking is done.  This
-   condition will always be satisfied if both x and y are positive.
-
+   b = ln(d), as is usually the case, then the routine returns ln(x*c + y*d).
+   Both x and y must be non-negative.  If either x or y is negative, it is 
+   treated as if it were zero.
 */
 PRECISION AddScaledLogs(PRECISION x, PRECISION a, PRECISION y, PRECISION b)
 {
-  return (a > b) ? a + log(x + y*exp(b-a)) : b + log(x*exp(a-b) + y);
+  if (x > 0)
+    if (y > 0)
+      return (a > b) ? a + log(x + y*exp(b-a)) : b + log(x*exp(a-b) + y);
+    else
+      return log(x) + a;
+  else
+    return (y > 0) ? log(y) + b : MINUS_INFINITY;
 }
 
 /*
-- 
GitLab