[R] Computing 'exp(1e3)*0' correctly....

Rolf Turner rolf.turner at xtra.co.nz
Sun Sep 2 01:43:10 CEST 2012


On 02/09/12 10:52, CHEL HEE LEE wrote:
> I have some trouble to deal the value of 'NaN'.  For example,
>
>> exp(1e3)
> [1] Inf
>> exp(1e3)*0
> [1] NaN
>
> The correct answer should be 0 rather than NaN.  I will very appreciate
> if anyone can share some technique to get a correct answer.

There is no technique that will consistently give you a "correct" answer.

What you seem to want is "x*0 = 0" if "x" is a number that is so large
that it cannot be stored as a floating point number (e.g. x = exp(1e3))
and hence is represented as "Inf".

At the same time you presumably would want "x*0 = NaN" if "x is genuinely
infinite" (e.g. x = 1/0).

But R will have no way of knowing which sort of "Inf" it is dealing with 
when
it is called upon to calculate "x*0".

You simply have to be more careful in your coding and avoid expressions like
exp(a)*b when there is a possibility that "a" could be a large positive 
number
and "b" could be 0.  E.g. you *might* want to recode exp(a)*b as exp(a + 
log(b)).
Note that exp(1e3 + log(0)) does indeed evaluate to 0 as you desire. OTOH
exp(1/0 + log(0)) evaluates to NaN, as it should.

There are still perils lurking in this strategy, I think.

Bottom line:  Be very carefully in your coding when overflow/underflow 
problems
could potentially arise.  There are no general prescriptions; every new 
instance
has its own difficulties and its own solution.

HTH

     cheers,

         Rolf Turner




More information about the R-help mailing list