[R] Recursive Computation in R

Ko-Kang Wang Ko-Kang at xtra.co.nz
Tue Apr 25 05:06:00 CEST 2000


Hi there,

I have written a function to calculate factorials as follows:

fact <- function(x) {
     recurse <- x > 1
     x[!recurse] <- 1
     if( any(recurse) ) {
          y <- x[recurse]
          x[recurse] <- y * fact( y - 1 )
     }
     x
}


I want to be able to do the famous birthday problem, which will involve
the computation of 365!, however it shall get cancelled out during the
computation.  To make it more clear, I want to work out:
n <- 1:80
prob <- 1 - ( fact(365) / ( fact( 365 - n ) * 365 ^ n ) )

This, if works, should gives a vector of 80 probabilities, that given a
room of n people, 2 will share the same birthday.

But R gives me the following Error message:
Error in fact(y - 1) : evaluation is nested too deeply: infinite
recursion?

I assume that 365 is simply too large?  Which should imply that my
factorial function is not written to the optimised way.  Anyone can
offer a solution?  Much appreciated.


Sincerely,

-------------------------------------------
Ko-Kang Wang
University of Auckland
Auckland 1005
New Zealand

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list