Why is R doing the wrong amount here?

(If the answer is really how R uses binary numbers to store small decimal places, it will still be interesting to hear details about why this comes from someone who has knowledge about it)

I use R to calculate the sum, in particular this one:

enter image description here

Here is my R code:

r = 21 #Number of times the loop executes n = 52 sum = 0 #Running total for(k in 0:r){ sum = sum + (1-(choose(2^(k), n)*(factorial(n)/(2^(n*k))))) print(sum) } 

If you look at the result, you will notice:

 [1] 1 [1] 2 ... [1] 11.71419 [1] 11.71923 [1] 11.72176 [1] 12.72176 [1] 13.72176 

Why does it start to increase by 1 after the 19th iteration?

Are there other freely available computing mechanisms that are better suited to this task?

+5
source share
2 answers

All calculations here use floating point numbers, which, as a rule, are poorly suited for factorials and increasing powers (since such values ​​quickly become very large, which makes the calculations less accurate).

Please, try:

 > factorial(52)/(2^(52*19)) [1] 3.083278e-230 > factorial(52)/(2^(52*20)) [1] 0 

and compare with Pari-GP:

 ? \p 256 realprecision = 269 significant digits (256 digits displayed) ? precision( (52!) / 2^(52*19) + . , 24) %1 = 3.08327794368108826958435659488643289724 E-230 ? precision( (52!) / 2^(52*20) + . , 24) %2 = 6.8462523287873017654100595727727116496 E-246 
+5
source

If you are looking for a way around the overflow / deficiency problem you have, you can use the logs (to maintain acceptable values ​​for intermediate calculations) and then increase them at the end:

 options(digits=20) for(k in 0:r){ sum = sum + (1 - exp(lchoose(2^k, n) + log(factorial(n)) - k*n*log(2))) print(paste0(k,": ",sum)) } [1] "0: 1" [1] "1: 2" [1] "2: 3" ... [1] "19: 11.7217600143979" [1] "20: 11.7230238079842" [1] "21: 11.7236558993777" 

To make sure this is correct, I performed the initial summation (excluding journals) in Mathematica and got the same results up to 12 decimal places.

Although you can make the problem in R if you want to go with a computer algebra system (which allows you to do symbolic mathematical calculations and exact calculations), Sage is free and open source.

+5
source

Source: https://habr.com/ru/post/1237512/


All Articles