2

I am trying to implement a gamma function from scratch using the following rules:

  1. If z is equal to 1 we return 1;
  2. List item
  3. gama(z) (using the recursion of the function) (z-1)*gamma(z-1);
  4. If z is a natural number then we return the factorial of (z-1);
  5. If z is equal to 1/2 we return sqrt(pi).

This conditions leads me to the following more simplified conditions

  1. If z is natural we use the third property;
  2. If z is the shape of b/2 where b is a natural number we use the property 2 and 4.
  3. Else we apply the second formula until n is lesser than 1. When z is lesser than 1 we apply this formula: Formula for gamma(z)

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
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
bSwizzle
  • 73
  • 8

1 Answers1

2

You can try the code below

fg <- function(z) {
  integrate(function(x) exp(-x) * x^(z - 1), 0, Inf)
}

and you will see

> fg(10)
362880 with absolute error < 0.025

> gamma(10)
[1] 362880

> fg(1.5)
0.8862265 with absolute error < 2.5e-06

> gamma(1.5)
[1] 0.8862269
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81