/ Published in: C
Given log(x) and log(y) compute log(x - y)
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/* Copyright (C) 2009 by Andrew Miller ([email protected]). * You may use this code under the GNU GPL version 3 (or at your option, any later version) * See http://www.gnu.org/licenses/gpl-3.0.txt * You may alternatively elect to use this code under the GNU LGPL version 3 (or at your * option, any later version) at http://www.gnu.org/licenses/lgpl-3.0.txt . * You may alternatively elect to use this code under the Mozilla MPL version 1.1 or later * (http://www.mozilla.org/MPL/MPL-1.1.html) * */ /* Given log(x) and log(y) compute log(x - y). */ double log_form_subtract(double log_x, double log_y) { if (log_x <= log_y) return 0.0/0.0; double diff = log_x - log_y; // If log(x) dominates, return it... if (diff > 708.0) return log_x; /* We use the following trick: * log(x-y) = log(a(x/a - y/a)) = log(a) + log(x/a - y/a) * = log(a) + log(exp(log(x)-log(a)) - exp(log(y)-log(a))) * We pick log(a) = (log(x) + log(y)) / 2. So * log(x-y) = (log(x) + log(y)) / 2 + * = log(exp((log(x) - log(y)) / 2) - exp((log(y) - log(x)) / 2)) */ diff /= 2.0; }