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?
Numbers in Geometric Progression
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
thank you, can u please see my comment above and tell me if i can write this code in that fashion? i am a newbie and hence have a lot of doubts :( –
Epilate
@Epilate - Josh's answer is what you want I reckon.
geomSeries(2,32)
as outlined in his response will give you a base 2 progression up until the max value of 32. –
Expressly thank you everybody! yes, @josh's answer was indeed helpful! cheers guys! –
Epilate
(Do be aware that the function above would need a much more checking and adjusting for edge and corner cases to be really ready for prime time. Try for instance
geomSeries(.1, 100)
, geomSeries(1, 1.001)
, and geomSeries(2, 0.8)
to see what I mean.) –
Lodicule 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)
when i want a sequence from say 1 to 100, incrementing by 10, i write: seq(1, 100, by=10). so now i want a sequence from 1 to say 1000 that increments geometrically like 1, then 2, then 4 and so on. –
Epilate
Something like this to get a geometric progression that always ends less than the number specified (the 1000 in this case):
2^(1:floor(log(1000,2)))
–
Expressly Suggest you have a look at
seq()
, as per baptiste's comment above. Do ?
and the function name to get help on an R function, so ?seq
. In this case you want something like seq(0, 10, by = 10)
. Note that goes from 0 to 100, not 1 to 100, which is not a regularly spaced series. –
Navarro 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
© 2022 - 2024 — McMap. All rights reserved.
2^seq(0, 5, by=1)
– Hematology