递归求和,使用泊松分布
Recursive sum, using Poisson distribution
我正在尝试在 R 中构建一个递归函数,
H(x,t) = \sum\limits_{d=0}^{x} (Pr(D=d)*(h*(x-d)+H(x-d,t-1)))
+ \sum\limits_{d=x+1}^{\infty} (Pr(D=d)*(p(*d-x)+ H(0,t-1)))
其中h,p是一些常数,D ~ Po(l) and H(x,0) = 0,这些是我到目前为止所做的代码,给出了一个明显的错误,但我看不到使固定。代码
p<- 1000 # Unit penalty cost for lost sales
h<- 10 # Unit inventory holding cost pr. time unit
l<- 5 # Mean of D
H <- function(x,t){
if(t==0)(return(0))
fp <- 0
sp <- 0
for(d in 0:x){
fp <- fp + dpois(x=d,l)*(h*(x-d)+H(x-d,t-1))
}
for(d in x+1:Inf){
sp <- sp + dpois(x=d,l)*(p*(d-x)+H(0,t-1))
}
return(fp+sp)
}
当我运行这样的时候,错误是
Error in 1:Inf : result would be too long a vector
这似乎很明显,所以问题是,任何人都可以指出我重新定义问题的方向,这样我就可以让 R 给我一个解决方案吗?
提前致谢。
从 x+1:Inf
开始是行不通的。由于您使用的是泊松 pdf,因此您只需添加一个上限(为什么?想想 pdf 的形状以及右尾的值有多小):
for(d in x+1:100)
当 运行 对于 H(20,2)
给出
[1] 252.806
当你增加到
for(d in x+1:500)
然后H(20,2)
也给出
[1] 252.806
我正在尝试在 R 中构建一个递归函数,
H(x,t) = \sum\limits_{d=0}^{x} (Pr(D=d)*(h*(x-d)+H(x-d,t-1)))
+ \sum\limits_{d=x+1}^{\infty} (Pr(D=d)*(p(*d-x)+ H(0,t-1)))
其中h,p是一些常数,D ~ Po(l) and H(x,0) = 0,这些是我到目前为止所做的代码,给出了一个明显的错误,但我看不到使固定。代码
p<- 1000 # Unit penalty cost for lost sales
h<- 10 # Unit inventory holding cost pr. time unit
l<- 5 # Mean of D
H <- function(x,t){
if(t==0)(return(0))
fp <- 0
sp <- 0
for(d in 0:x){
fp <- fp + dpois(x=d,l)*(h*(x-d)+H(x-d,t-1))
}
for(d in x+1:Inf){
sp <- sp + dpois(x=d,l)*(p*(d-x)+H(0,t-1))
}
return(fp+sp)
}
当我运行这样的时候,错误是
Error in 1:Inf : result would be too long a vector
这似乎很明显,所以问题是,任何人都可以指出我重新定义问题的方向,这样我就可以让 R 给我一个解决方案吗?
提前致谢。
从 x+1:Inf
开始是行不通的。由于您使用的是泊松 pdf,因此您只需添加一个上限(为什么?想想 pdf 的形状以及右尾的值有多小):
for(d in x+1:100)
当 运行 对于 H(20,2)
给出
[1] 252.806
当你增加到
for(d in x+1:500)
然后H(20,2)
也给出
[1] 252.806