Skip to content

Computing 'exp(1e3)*0' correctly....

5 messages · Chel Hee Lee, Jeff Newmiller, Rolf Turner +1 more

#
I have some trouble to deal the value of 'NaN'.  For example,
[1] Inf
[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.
#
I disagree that this answer is "wrong". If you want a mathematically correct answer you are going to have to obtain it by applying intelligence to the algorithm in which this calculation occurred. This is not a mailing list about numerical methods in general, so it probably isn't appropriate to pursue that conversation here.
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
--------------------------------------------------------------------------- 
Sent from my phone. Please excuse my brevity.
CHEL HEE LEE <gnustats at gmail.com> wrote:

            
#
On 02/09/12 10:52, CHEL HEE LEE wrote:
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
#
Em 02-09-2012 00:10, Jeff Newmiller escreveu:
Logarithms are the product of intelligence.
And the standard trick to make this sort of computation.

x <- 1e3
exp(x + log(0))  # zero

x <- 1e300
exp(x + log(0))  # zero

Rui Barradas
#
I very appreciate for good comments and tip regarding my question.  All
postings are excellent to know when I am writing such expression in R.
Thank you so much, and my question is completely resolved from all your
postings.
On Sun, 2012-09-02 at 00:50 +0100, Rui Barradas wrote: