I'm trying to implement the extended binomial density function with support on c( 0 : (floor(N) + 1)), but I'm running into (I think) precision issues, as running:
########################
#---DENSITY FUNCTION---#
########################
debinom <- function(k, n, p, sum) {
if (k <= n) {
return( choose(n, k) * p^k * (1-p)^(n-k) )
} else {
return (1.0 - sum)
}
}#END: pebinom
##########################################
#---CUMULATIVE DISTRIBUTION FUNCTION 2---#
##########################################
pebinom <- function(x, n, p) {
# point mass at 0
totalDensity = cumProb = debinom(0.0, n, p, 0.0)
k = 0
while (k <= (x)) {
density2 = debinom(k, n, p, totalDensity)
totalDensity = totalDensity + density2
cumProb = cumProb + density2
k = k + 1
}
k = k + 1
density = debinom(k, n, p, totalDensity)
cumProb = cumProb + density * (x - k)
return (cumProb)
}#END: debinom
############
#---TEST---#
############
for (i in 0:10) {
x = i + runif(1)
cat(x, " ", pebinom(x, 100, 0.1), "\n")
}
gives a negative probabilities for tail values.
EDIT
I have changed, and mostly simplified the routines along the comments and answers I've received:
#########################################
#---PROBABILITY DISTRIBUTION FUNCTION---#
#########################################
debinom <- function(k, n, p) {
if (k <=floor(n)) {
return( choose(n, k) * p^k * (1-p)^(n-k) )
} else if(k == (floor(n)+1)) {
cumProb = 0.0
for(i in 0 : floor(n)) {
cumProb = cumProb + debinom(i, n, p)
}
return (1.0 - cumProb)
} else {
return(0.0)
}
}#END: pebinom
########################################
#---CUMULATIVE DISTRIBUTION FUNCTION---#
########################################
pebinom <- function(x, N, P) {
cumProb = 0
for(i in 0 : (floor(x)) ) {
cumProb = cumProb + debinom(i, N, P)
}
return(cumProb)
}
kofpebinomshould be an integer and not a floating point number as intotalDensity = cumProb = pebinom(0.0,n,p,0.0). Also, it seems like you are including the point mass at $0$ twice intotalDensityandcumProb, once in the initialization and again when you callpebinomwithkequal to $0$. – Dilip Sarwate Nov 30 '11 at 15:37pebinomdoesn't fit the bill because it does not define a valid probability distribution unlesssumis identically 1. – whuber♦ Nov 30 '11 at 15:38