Numbers in Geometric Progression

China☆狼群 提交于 2019-12-10 12:33:16

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!