问题
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?
回答1:
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
回答2:
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)
回答3:
You can find any term in a geometric sequence with this mathematical function:
term = start * ratio ** (n-1)
Where:
term = the term in the sequence that you want
start = the first term in the sequence
ratio = the common ratio (i.e. the multiple that defines the sequence)
n = the number of the term in the sequence that you want
Using this information, write up a function in R that provides any subset of a geometric sequence for any start and ratio:
#begin = beginning of subset
#end = end of subset
geomSeq <- function(start,ratio,begin,end){
begin=begin-1
end=end-1
start*ratio**(begin:end)
}
geomSeq(1, 2, 1, 10)
# [1] 1 2 4 8 16 32 64 128 256 512
geomSeq(10,3,1,8)
# [1] 10 30 90 270 810 2430 7290 21870
geomSeq(10,3,4,8)
# [1] 270 810 2430 7290 21870
More on geometric sequences
来源:https://stackoverflow.com/questions/11094822/numbers-in-geometric-progression