Vahid Borji
2020-Jun-01 10:49 UTC
[R] How to create a warning inside the factorial function for decimal numbers
I am writing a code for the factorial function. My code is as follows:> f<- function(n){+ factorial <- 1+ if( n < 0 )+ print("Factorial of negative numbers is not possible")+ else if( n == 0 )+ print("Factorial of 0 is 1")+ else {+ for(i in 1:n)+ factorial <- factorial * i+ print(paste("Factorial of ",n," is ",factorial))+ }+ }My problem with this code is for decimal numbers as input. For example for f(6.5) my code computes 720, but we know 6.5 ! does not exist. For decimal numbers like, or sqrt(2) I would like to see a message like "The factorial for this number does not exist". How can I fix this problem in my code? [[alternative HTML version deleted]]
peter dalgaard
2020-Jun-01 11:00 UTC
[R] How to create a warning inside the factorial function for decimal numbers
You might check that n %% 1 == 0. (Factorials do exist for fractional numbers -- check e.g. factorial(6.5). And please don't send HTML because, well, you can see the result below) - pd> On 1 Jun 2020, at 12:49 , Vahid Borji <vahid.borji65 at gmail.com> wrote: > > I am writing a code for the factorial function. My code is as follows: > >> f<- function(n){+ factorial <- 1+ if( n < 0 )+ print("Factorial of negative numbers is not possible")+ else if( n == 0 )+ print("Factorial of 0 is 1")+ else {+ for(i in 1:n)+ factorial <- factorial * i+ print(paste("Factorial of ",n," is ",factorial))+ }+ } > > My problem with this code is for decimal numbers as input. For example for > f(6.5) my code computes 720, but we know 6.5 ! does not exist. For decimal > numbers like, or sqrt(2) I would like to see a message like > > "The factorial for this number does not exist". > > How can I fix this problem in my code? > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see > 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.-- Peter Dalgaard, Professor, Center for Statistics, Copenhagen Business School Solbjerg Plads 3, 2000 Frederiksberg, Denmark Phone: (+45)38153501 Office: A 4.23 Email: pd.mes at cbs.dk Priv: PDalgd at gmail.com