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.
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:>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. > >______________________________________________ >R-help at r-project.org mailing list >https://stat.ethz.ch/mailman/listinfo/r-help >PLEASE do read the posting guide >http://www.R-project.org/posting-guide.html >and provide commented, minimal, self-contained, reproducible code.
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