Saturday, July 9, 2011

Debugging puzzle in R

Here's a small debugging puzzle in R. I recently came ran into it and thought that the bug was rather elegant. I have simplified down the problem I faced, but not all the way to keep a little fun in.

Explain the output
>> # a is a (large) vector with numerical elements
>> any(is.nan(a))

>> any(is.nan(exp(a)))

>> any(is.nan(exp(1.0 * a)))

>> any(is.nan(exp(0.0 * a)))
[1] TRUE

See something surprizing? Suddenly a NaN where there was none before?

Can you think why this is happening?

If you give up, then click-and-drag to select and see the hint below:

>> # Multiplying an Infinity with zero gives a NaN
>> Inf * 0
[1] NaN


No comments: