Reputation: 53
I have the equation C.sul.f = C.sul.i + (R * C.sil.i) / (1 + R/D), where C.sul.i = 200000, C.sil.i = 100, R = 100, and D = 2130.
The calculation requires that the for every iteration from 1:100000, the C.sul.f from the previous iteration is used for the C.sul.i of the current iteration. Essentially,
Iteration 1 --> C.sul.f1 = C.sul.i + (R * C.sil.i) / (1 + R/D)
Iteration 2 --> C.sul.f2 = C.sul.f1 + (R * C.sil.i) / (1 + R/D)
Iteration 3 --> C.sul.f3 = C.sul.f2 + (R * C.sil.i) / (1 + R/D)
.
.
Iteration n --> C.sul.fn = C.sul.fn-1 + (R * C.sil.i) / (1 + R/D)
Could I please get some help how I would structure this script in R
I appreciate any help.
Thank you in advance.
Upvotes: 1
Views: 156
Reputation: 101618
If you like to have a recursion answer, you can try defining a user function f
like below
f <- function(n) {
if (n==1) return(c.sul.i + (R * c.sil.i) / (1 + R/D))
f(n-1) + (R * c.sil.i) / (1 + R/D)
}
For efficiency considerations, answer by @SirTain using a math solution is the best.
Upvotes: 0
Reputation: 369
niko has an excellent solution using Reduce
, but for your example (and for all series) I recommend first applying a bit of series reduction to see if there's a simple general solution.
In your series, the only recursive element is effectively a constant value added to the previous one. If you expand it out, it becomes fairly obvious:
C.sul.f1 = C.sul.i + (R * C.sil.i) / (1 + R/D)
C.sul.f2 = C.sul.i + (R * C.sil.i) / (1 + R/D) + (R * C.sil.i) / (1 + R/D)
C.sul.f3 = C.sul.i + (R * C.sil.i) / (1 + R/D) + (R * C.sil.i) / (1 + R/D) + (R * C.sil.i) / (1 + R/D)
in general:
C.sul.fn = C.sul.i + n * ((R * C.sil.i) / (1 + R/D))
So for the most efficient function, I recommend:
c_sul_i <- 200000
c_sil_i <- 100
R <- 100
D <- 2130
C.sul.fn <- function(n) {
return(C.sul.i + n * (R * C.sil.i) / (1 + R/D) )
}
sapply(1:100000,C.sul.fn)
Or, if you prefer single line implementation:
sapply(1:100000,function(x) {C.sul.i + x * (R * C.sil.i) / (1 + R/D)})
Upvotes: 2
Reputation: 5281
This is the archetype of problem Reduce
solves:
c_sul_i <- 200000
c_sil_i <- 100
R <- 100
D <- 2130
Reduce(
f = function(x, y) x + (R * c_sil_i) / (1 + R/D),
x = 1:5,
init = c_sul_i + (R * c_sil_i) / (1 + R/D),
accumulate = TRUE
)
# [1] 209551.6 219103.1 228654.7 238206.3 247757.8 257309.4
PS: Note that for example purposes I only computed the first 5 values. For your case just swap 1:5
with 1:100000
.
Upvotes: 3