Reputation: 187
I'm trying to write a R program to calculate the sum of a geometric series without using the standard formula as shown below:
h <- function(x,n){
sum.value <- 1
i <- 1
while ( i <= n){
sum.value = sum.value + x^i
}
return(sum.value)
}
When I run this code, it goes into an infinite loop. I didn't have trouble when running it using a for loop. Its really strange that the same doesn't work with a while loop as is said that a while loop is more fundamental that a for loop. Have I missed something? Thanks.
Upvotes: 1
Views: 5477
Reputation: 100
A for loop in R increments automatically. A while loop does not. You need to add an increment to i inside your while loop if you want it to work.
Upvotes: 1
Reputation: 132576
You forgot to increase i
. Also I don't understand why sum.value
starts with 1.
h <- function(x,n){
sum.value <- 0
i <- 1
while ( i <= n){
sum.value = sum.value + x^i
i <- i+1
}
return(sum.value)
}
h(3,5)
#[1] 363
Of course, it would be much more efficient and simpler to use vectorization:
sum(3^(1:5))
#[1] 363
Upvotes: 3