Hi:

Is this what you're looking for?

x <- 1:10
1 + sum((1/x)^(1:10))
[1] 2.291286
1 + sum(x^(-(1:10)))
[1] 2.291286

Since this may be a homework question, I'll let you figure out how to turn
it into a function - it only needs one change.


On Tue, Nov 9, 2010 at 7:16 PM, vicho <vicho@ucla.edu> wrote:

>
> I want to make a function for geometric seqeunce
>
> since
>
> testing=function(x){i=1;ans=1;while(true){ans=ans+(1/x)^i ; i=i+1}
> ;return(ans)}
>

I presume the code as written was the best way you knew to convey your
meaning, but writing out the mathematical function would have been helpful.
As it appears you're coming from a C(++?) background, you should be made
aware that R can do vectorized arithmetic, so there is much less dependence
on iteration than in conventional programming languages. My code (which I
*hope* is what you meant) illustrates vectorization in the following ways:
   * raising the individual elements of x (or 1/x) to its
     corresponding exponent - both x and the sequence 1:10 are vectors,
     whose result is a vector;
   * summing the resulting vector.
Vectorization is one of the most powerful features of R. (So is indexing,
but that's a topic for another day...)


> doesn't work... the program is freeze... from my research, i know i should
> use iterators.
>

or not...much of research is learning to unlearn what you've learned and try
new ways of doing things.

>
> I read iterators.pdf at
> http://cran.r-project.org/web/packages/iterators/iterators.pdf and didnt
> find it helps solving my problem at all...
>
> Is there any sources I can look up to?
>

Reading the Introduction to R document that comes with the software would be
a good start. It has many examples that illustrate vectorization and
indexing, among other important topics. It won't make you an overnight
expert, but it will teach you to think of programming from a different
angle.

>
> Thanks
> Ting
>

HTH,
Dennis

> --
> View this message in context:
> http://r.789695.n4.nabble.com/Performing-a-geometric-seqeunce-using-iterators-tp3035465p3035465.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]

