Search code examples
c#linqsequencesenumerableinfinite-sequence

Linq statement for an infinite sequence of successive halves


Given a starting number, imagine an infinite sequence of its successive halves.

1, 0.5, 0.25, 0.125, ...

(Ignore any numerical instabilities inherent in double.)

Can this be done in a single expression without writing any custom extension methods or generator methods?


Solution

  • I don't know of a single-expression way but I found this clever generator code here: http://csharpindepth.com/articles/Chapter11/StreamingAndIterators.aspx

    public static IEnumerable<TSource> Generate<TSource>(TSource start,
                                                      Func<TSource,TSource> step)
    {
       TSource current = start;
       while (true)
       {
           yield return current;
           current = step(current);
       }
    }
    

    In your case you'd use it:

    foreach (double d in Generate<double>(1, c => c / 2))
    {
        ...
    }