[R] Right digits of a floating number

Duncan Murdoch murdoch.duncan at gmail.com
Wed Jul 28 01:33:17 CEST 2010


On 27/07/2010 6:34 PM, vincent.deluard wrote:
> 
> Hi all,
> 
> I am dealing with very large numbers but I am only interested in their last
> digits.
> 
>> 244^244
> [1] Inf
> 
> As far as I can tell, the largest number R can take has 308 digits (1+E308).
> Is there a way I could see the last digits only of 244^244?
> 
> Many thanks for your help.
> 
> Vincent Deluard, CFA.


Use the facts that the last digits of X are equal to X modulo 10^n, for 
some n, and that X*Y modulo Z = (X modulo Z) * (Y modulo Z) modulo Z. 
Then you can calculate it easily in base R, as long as n is no more than 
7 (so that the individual multiplications don't overflow).  For example,

 > result <- 1
 > for ( i in 1:244)
+ result <- (result * 244) %% 1000
 > result
[1] 496

Duncan Murdoch



More information about the R-help mailing list