Reputation: 53
I am trying to speed up a Monte Carlo function. I want to tighten this up but I can't figure out how. Any ideas?
initial=1400
ppinitial=0.07
assets2020=numeric(41)
actual=round(seq(from=initial, to=0, by=(-initial/40)),0)*100000
assets2020[1]=1000000*1.02-actual[1]*ppinitial
for (i in 2:length(actual)){
assets2020[i]=assets2020[i-1]*1.02-actual[i]*ppinitial}
Upvotes: 1
Views: 94
Reputation: 121568
I think that you can use filter
here:
assets2020 <- -ppinitial * filter(actual,1.02,'rec',init=-1000000/ppinitial)
y[i]=y[i-1]*1.02-x[i]*pp ## use y ,x notation more handy than long variables
can be rewritten:
Y[i]= x[i]+f[1]*Y[i-1] ## recursive filter expression
Where Y = -y/pp
and f[1]=1.02
Or Y[1]=x[1]+f[1]*1000000
so init
is equal to -1000000/ppinitial
ppinitial =100
filter_asset <- -ppinitial * filter(actual,1.02,'rec',init=-1000000/ppinitial)
sum(abs(filter_asset-assets2020))
[1] 0.001937866
Upvotes: 1