2
$\begingroup$

With double precision, I get $\log(\exp(-3)+1)=0.048587351573741958$, which already has $4$ incorrect digits, and $\log(\exp(-30)+1)=9.348... \times10^{-14}$, which only has two correct digits.

What is the most elegant way to circumvent this? I tried a Taylor series of $\log(y)$ around $y=1$, but even with 14 terms I still didn't get all digits correctly for $x=-3$.

$\endgroup$
12
$\begingroup$

Use the (IEEE standard) library function log1p, which should be present in all programming languages. The function log1p(x) returns $\log(1+x)$, and is implemented with particular attention to accuracy when $x$ is small. It is designed to solve exactly this kind of problem.

$\endgroup$
4
$\begingroup$

If you want to use your own implementation to evaluate the function, take a look on this article. Otherwise, just go with log1p as suggested by @Frederico Poloni in his answer.

For more information about the log1p function read this other article from the same author.

$\endgroup$
  • 2
    $\begingroup$ Second link hits the nail on the head, much to my embarrassment I have never thought about these issues $\endgroup$ – Bananach Dec 16 '17 at 21:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.