The formula for the sum of the series 1 + 2 + ... + n is (n(n+1)/2. What if we weren’t sure that was the right function? How could we check? Using what we learned about functions we can create one that computes the S_n:
compute_s_n <- function(n){
x <- 1:n
sum(x)
}
How can we compute S_n for various values of n, say n=1,...,25 ? Do we write 25 lines of code calling 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 n. For-loops let us define the range that our variable takes (in our example n=1,...,10, then change the value and evaluate expression as you loop.
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 \(S_n\) example:
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 n=1, n=2, etc…, we compute S_n and store it in the nth entry of s_n
.
# Create a compute_s_n function to sum up 1^2 + 2^2 + ... + n^2.
compute_s_n <- function(n){
x <- 1:n
sum(x)
}
# S_n example.
m <- 25
s_n <- vector(length = m) # create an empty vector
for(n in 1:m){
s_n[n] <- compute_s_n(n)
}
z <- s_n[25]
# print the sum of squres.
z
# Create a compute_s_n function to sum up 1^2 + 2^2 + ... + n^2.
compute_s_n <- function(n){
x <- 1:n
sum(x^2)
}
# S_n example.
m <- 25
s_n <- vector(length = m) # create an empty vector
for(n in 1:m){
s_n[n] <- compute_s_n(n)
}
z <- s_n[25]
# print the sum of squres.
z
msg = "Please check the function to get the correct value in z."
test_function("compute_s_n")
test_object("z", undefined_msg = msg, incorrect_msg = msg)
success_msg("Great! Head over to the next exercise.")