Making a binomial expansion in R

Viewed 119

I was working on a binomial expansion in R, I came across some issues and I feel the values do not make sense. Here is my code, I used factorial and combination from "scratch" to compute. I tried x=6, y=2 and n=4 I got 2784 as an answer. If I try 1 it gives 0. If n=i I get infinity because the denominator would equal zero

  fact=1
  for(i in 1:n){
    fact=fact*i
  }
  return(fact)
}

Combi<-function(n,r){
  result=f(n)/(f(r)*f(n-r))
  return(result)
}
Combi(6,4)
expand.binomial<-function(x,y,n){
  sumz=0
  for(i in 1:n){
    if(i==n){
      break
    }
      sumz=sumz+Combi(n,i)*(x**i)*(y**(n-i))
  }
  return(sumz)
}
1 Answers

You should be aware of that, 0! is 1. In this case, f should be defined like below

f <- function(n) {
  if (n == 0) {
    return(1)
  }
  fact <- 1
  for (i in 1:n) {
    fact <- fact * i
  }
  return(fact)
}

Also, in expand.binomial, the exponents should start from 0 to n, i.e.,

expand.binomial <- function(x, y, n) {
  sumz <- 0
  for (i in 0:n) {
    sumz <- sumz + Combi(n, i) * (x**i) * (y**(n - i))
  }
  return(sumz)
}

Test

> expand.binomial(6, 2, 4)
[1] 4096

> expand.binomial(6, 2, 1)
[1] 8

> expand.binomial(6, 2, 0)
[1] 1
Related