R function to approximate geometric series

Viewed 47

I would like to ask how to calculate an approximation for simple geometric series (examples bellow) using R and without loops.

1-(1/3)+(1/5)-(1/7)+(1/9)-(1/11)

1+(1/3^2)+(1/5^2)+(1/7^2)+(1/9^2)

I have no idea how to calculate approximation for geometric series using R, although it might be quite simple. Please help me :)

I tried to create a function, but because I'm not familiar with geometry itself I failed.

1 Answers

We could create a sequence vector with seq, multiply the alternate elements with -1 to change the sign ('v2'), divide and get the sum

v1 <- seq(3, 11, by = 2)
v2 <- rep(c(-1, 1), length.out = length(v1))
sum(c(1, v2 * (1/v1)))
[1] 0.7440115

Or may also use

sum(1/seq(1, 11, by = 2) *c(1, -1))
[1] 0.7440115

checking with OP's output

> 1-(1/3)+(1/5)-(1/7)+(1/9)-(1/11)
[1] 0.7440115

For second case,

v11 <- seq(1, 9, by = 2)
sum(1/v11^2)
[1] 1.183865

OP's output

> 1+(1/3^2)+(1/5^2)+(1/7^2)+(1/9^2)
[1] 1.183865
Related