The formula for the sum of the series
compute_s_n <- function(n){
x <- 1:n
sum(x)
}
How can we compute compute_s_n
?
No, that is what for-loops are for in programming. In this case, we are
performing exactly the same task over and over, and the only thing that
is changing is the value of
Perhaps the simplest example of a for-loop is this useless piece of code:
for(i in 1:5){
print(i)
}
#> [1] 1
#> [1] 2
#> [1] 3
#> [1] 4
#> [1] 5
Here is the for-loop we would write for our
m <- 25
s_n <- vector(length = m) # create an empty vector
for(n in 1:m){
s_n[n] <- compute_s_n(n)
}
In each iteration s_n
.
Now we can create a plot to search for a pattern:
n <- 1:m
plot(n, s_n)
If you noticed that it appears to be a quadratic, you are on the right
track because the formula is
head(data.frame(s_n = s_n, formula = n*(n+1)/2))
#> s_n formula
#> 1 1 1
#> 2 3 3
#> 3 6 6
#> 4 10 10
#> 5 15 15
#> 6 21 21
We can also overlay the two results by using the function lines
to draw a line over the previously plotted points:
plot(n, s_n)
lines(n, n*(n+1)/2)