I am trying to implement a gamma function from scratch using the following rules:
- If z is equal to 1 we return 1;
- List item
- gama(z) (using the recursion of the function) (z-1)*gamma(z-1);
- If z is a natural number then we return the factorial of (z-1);
- If z is equal to 1/2 we return sqrt(pi).
This conditions leads me to the following more simplified conditions
- If z is natural we use the third property;
- If z is the shape of b/2 where b is a natural number we use the property 2 and 4.
- Else we apply the second formula until n is lesser than 1. When z is lesser than 1 we apply this formula:
My code looks something like this, but I can't seem to make it work for values that go to the criteria from point 8.
gama <-function(z){
fgama <- function(x)
{
x**(z-1)*exp(-x)
}
functie <-integrate(fgama,0,Inf)
if(z==1/2)
{
return (sqrt(pi))
}
if(isNatural(z))
{
return(factorial(z-1))
}
if(z%%2==0.5 || z%%2==1.5){
return((z-1)*gama(z-1))
}
else
{
while(z > 1)
{
n <- (z-1)*gama(z-1)
}
return(functie)
}
}
print(gama(4.3))
It gives this error:
Error in (z - 1) * gama(z - 1) : non-numeric argument to binary operator