10

<math.h> provides a more accurate method for computing log(1+x) for doubles.

Is there a similarly precise manner for computing log(1-x)?

The reason I ask is because I'm trying to do some work in log-space for greater precision (I'm mostly multiplying and summing numbers very close to zero). I found it easy to write a function that gives log( exp(log_of_a) + exp(log_of_b) ) = log( a + b ) by using log1p. I am trying to make a similar function for the difference:

log( exp(log_of_a) - exp(log_of_b) ) = log( a - b ) where a > b, of course.

Essentially, as long as neither log_a or log_b == -inf, the function should simply return:

return log( 1 - exp(log_b-log_a) ) + log_a;

In my log_add function, I end up with a log( 1 + ... ), and so I use log1p. But here I have log( 1 - ... ). Just in case, I even googled log1m, but no luck...

When the argument x is in the range [-inf, 1), then I could simply use log1p(-x) (given my assertion a > b).

Is that the best way to go about solving this? I feel I must be doing work that has been done before...

I'd really appreciate your help knowing how to get the most accurate results I can (or explaining why I can't get results more accurate than this).

user
  • 7,123
  • 7
  • 48
  • 90

1 Answers1

17

@Raymond Chen is spot on: "Negation of floating point numbers is exact, so log1p(-x) is as accurate as log1p(x)." Just making it into a real answer.

StilesCrisis
  • 15,972
  • 4
  • 39
  • 62
  • 3
    log1p(-x) is indeed a fine way to do it, but I think this answer is misleading in that it sounds like it's making a precise statement but it's really not. If you think it is, please say exactly what you mean by "is as accurate", and then clarify the leap from "negation of floating point numbers is exact" to "log1p(-x) is as accurate as log1p(x)". – Don Hatch Jun 28 '15 at 06:29