[R] How to create a warning inside the factorial function for decimal numbers
peter dalgaard
pd@|gd @end|ng |rom gm@||@com
Mon Jun 1 13:00:18 CEST 2020
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 using 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 using 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 using cbs.dk Priv: PDalgd using gmail.com
More information about the R-help
mailing list