How can i generate a sequence of numbers which are in Geometric Progression in R? for example i need to generate the sequence : 1, 2,4,8,16,32 and so on....till say a finite value?
A geometric sequence is a sequence of numbers that follows a pattern were the next term is found by multiplying by a constant called the common ratio, r. an=an−1⋅roran=a1⋅rn−1. Example. Write the first five terms of a geometric sequence in which a1=2 and r=3.
1, 2, 4, 8, 16, 32, 64, 128, 256, ... This sequence has a factor of 2 between each number. Each term (except the first term) is found by multiplying the previous term by 2.
This is a geometric sequence since there is a common ratio between each term.
Here's what I'd do:
geomSeries <- function(base, max) {
base^(0:floor(log(max, base)))
}
geomSeries(base=2, max=2000)
# [1] 1 2 4 8 16 32 64 128 256 512 1024
geomSeries(3, 100)
# [1] 1 3 9 27 81
Why not just enter 2^(0:n)? E.g. 2^(0:5) gets you from 1 to 32 and so on. Capture the vector by assigning to a variable like so: x <- 2^(0:5)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With