Crimson
Crimson

Reputation: 157

log1p function in MATLAB

Can anyone please help clarifying what is the meaning of the following sentence in log1p reference page.

y = log1p(x) computes log(1+x), compensating for the roundoff in 1+x.

I look at the source code and I do not understand how rewriting a function as follows helps:

p1 = xs + 1;
careful = xs.*log(p1)./(p1-1);

Does it mean in MATLAB the round-off error of (xs+1) is worse than the log function when a xs is small?

Thanks in advance.

Upvotes: 0

Views: 365

Answers (1)

Mingjing Zhang
Mingjing Zhang

Reputation: 943

First, the round-off error of (xs + 1) for small xs is not a MATLAB-specific problem, but a natural result of how a double precision number is represented in most popular computer languages. IEEE 754 double number allows only ~16 significant decimal digits. When you add two numbers that are separated by more than 16 orders of magnitude, say 1 and 1e-32, the result 1.000...[32x]...0001 cannot all fit into a double number, and the 1e-32 part will be effectively truncated, so you will get 1 + 1e-32 == 1. That's where the rounding error comes from.

In your code snippet, when xs is small enough, p1 will =1, then careful will become NaN. When this happens, you know xs is too small to be used in the regular calculation process, so we might as well just return xs instead. However, note that this is not the official source of log1p in MATLAB, but rather it is someone else's empirical solution intended to mimic the behavior of log1p.

Upvotes: 1

Related Questions