Reputation: 631
Calculate the $\sum_{j=1}^{n}r^j$
where r has been assigned the value $1.06$
,and compare with \frac{(1-r^{n+1})}{(1-r)} for $n=10,20$
.
This is what I have done so far.
j=c(1:10)
r=1.06
A=r^j
A
sum(A)
compare_with=(1-(1.06)^(11))/(1-(1.06))
compare_with
Upvotes: 0
Views: 113
Reputation: 76470
I believe this is simpler than what the discussions in the comments are making it look. In R, all arithmetic operations are vectorized, so the code below works for a vector n
.
compare_with <- function(n, r) (r - r^(n + 1))/(1 - r)
n <- c(10, 20, 30, 40)
j <- 1:10
r <- 1.06
A <- r^j
sum(A)
#[1] 13.97164
compare_with(n, r)
#[1] 13.97164 38.99273 83.80168 164.04768
If the function needs to also be vectorized over r
, it's once again not that complicated.
CompareWith <- Vectorize(compare_with, "r")
r_vec <- c(1.06, 1.08)
CompareWith(n, r_vec)
# [,1] [,2]
#[1,] 13.97164 15.64549
#[2,] 38.99273 49.42292
#[3,] 83.80168 122.34587
#[4,] 164.04768 279.78104
Upvotes: 1
Reputation: 1834
You have made an error in the formula for compare_with
. First of all you define r
but don't use it in compare_with
. It is much better to use variables you define so that when you change a value you don't have to change it all over the place with the risk of forgetting to change some part.
Your compare_with
is wrong. It should read
compare_with=(1.06-(1.06)^(11))/(1-(1.06))
You can prove this the standard way for geometric series.
Secondly there is absolutely no need to use c
in the definition of j
; just j <- 1:n
is sufficient. And you should define n
before you start.
A nicer way of writing your formulas is
n <- 10
j <- 1:n
r <- 1.06
A <- r^j
A
sum(A)
compare_with=(r-r^(n+1))/(1-r)
compare_with
If you follow @Rui_Barradas's advice the compare_with
function should be written as:
compare_with <- function(n) (r - r^(n + 1))/(1 - r)
BTW: In your question you say that r
has been assigned the value 1.08
. Yourcalculations use the value 1.06
. So what is it?
Additional method
To do what you specify in your comment you could do that this way.
Define a function A
that can take a vector of values for n
like this
A <- function(n) { Asum <- function(n) sum(r^(1:n)); sapply(n,Asum) }
Then this will do what you want
n <- c(10,20,30,40)
compare_with(n)
A(n)
Upvotes: 2
Reputation: 574
j <- 1:10
j.compare <- c(10,20)
sum(1.08^j) #sum
(1-1.08^j.compare)*((1-1.08)^-1) #compare with
Upvotes: 2