# [R] creating a reverse geometric sequence

David Winsemius dwinsemius at comcast.net
Sun May 23 21:04:51 CEST 2010

```On May 23, 2010, at 1:43 PM, Erik Iverson wrote:

> Hello,
>
> Can anyone think of a non-iterative way to generate a decreasing
> geometric sequence in R?
>
> For example, for a hypothetical function dg, I would like:
>
> > dg(20)
> [1] 20 10 5 2 1
>
> where I am using integer division by 2 to get each subsequent value
> in the sequence.

> dg <- function(ratio, len) (ratio)^( 0:(len-1) )

> 20*dg(.5, 20)
[1] 2.000000e+01 1.000000e+01 5.000000e+00 2.500000e+00 1.250000e+00
6.250000e-01
[7] 3.125000e-01 1.562500e-01 7.812500e-02 3.906250e-02 1.953125e-02
9.765625e-03
[13] 4.882812e-03 2.441406e-03 1.220703e-03 6.103516e-04 3.051758e-04
1.525879e-04
[19] 7.629395e-05 3.814697e-05

> (20*dg(.5, 20))[1:19] / (20*dg(.5, 20))[2:20]
[1] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2

>
>
> There is of course:
>
> dg <- function(x) {
>  res <- integer()
>  while(x >= 1) {
>    res <- c(res, x)
>    x <- x %/% 2
>  }
>  res
> }
>
> > dg(20)
> [1] 20 10  5  2  1
>
> This implementation of 'dg' uses an interative 'while' loop.  I'm
> simply wondering if there is a way to vectorize this process?
>
> Thanks,
> Erik
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help