[R] How to handle large numbers?

Stefan Evert stefan.evert at uos.de
Wed Feb 11 12:59:17 CET 2009


>> 2, I need to calculate e.g. exp(a)/(exp(b)+c), where both a and b  
>> are very
>> large numbers (>>1000, e.g a=1000, b=1007, and c=5). R gives me NaN  
>> when I
>> use the following command:
>>
>>> exp(1000)/(exp(1007)+5)
>> [1] NaN
>>
>> I am pretty sure this should be close to zero.
>
> No. It should be close to 1. Try  1000/(1000+5) for a simpler example.

Shouldn't it rather be 1 / exp(7), since exp(1007) = exp(1000) * exp(7)?

You can get the correct solution if you rewrite the fraction  
algebraically first, dividing all terms by exp(1000).

1 / (exp(7) + 5 * exp(-1000))

[1] 0.000911882

Of course, you have to know which of the numbers are large in order to  
do this right ...



Best regards,
Stefan Evert

[ stefan.evert at uos.de | http://purl.org/stefan.evert ]



More information about the R-help mailing list