I want to sum (1/3) (3/5) ⋯ (99/101) using loops in R I have tried this and I want to check if its right and is there other solutions also if we can do it with for loops and repeat loops.
sum <- 0
i <- 1
j <- 3
while (i<=99 && j<=101 ) {
sum <- sum i/j
i <- i 2
j <- j 2
}
print(sum)
CodePudding user response:
Yes, it is correct. Although you can also do
sum <- 0
i <- 1
while (i<=99) {
sum <- sum i/(i 2)
i <- i 2
}
sum
sum <- 0
for (i in seq(1,99,2)) {
sum <- sum i/(i 2)
}
sum
sum <- 0
i <- 1
repeat {
sum <- sum i/(i 2)
if (i == 99) break
i <- i 2
}
sum
i <- seq(1,99,2)
sum(i / (i 2))
Ah, you'd better use another name than sum
for your variable.
CodePudding user response:
Your implementation seems fine. If you want to try for loops it can be
sum <- 0
for (i in seq(1, 99, 2)){
sum <- sum i/(i 2)
}
CodePudding user response:
We can use the idea of odd numbers formula where 2*n - 1
and 2*n 1
are two consecutive odd numbers
result <- 0
for(i in 1:50){
result <- result (2*i - 1)/(2*i 1)
}
- output
result
#>[1] 46.10465