tags:

views:

44

answers:

2

Is there a compact, built-in way to generate a range of floats from min to max with a given step?

E.g.: range(10, 20, 0.1) [but built-in].

+3  A: 

No, there's nothing built in. It would be really easy to write your static method though. Something like:

public static IEnumerable<float> FloatRange(float min, float max, float step)
{
    for (float value = min; value <= max; value += step)
    {
        yield return value;
    }
}

EDIT: An alternative using multiplication, as suggested in comments:

public static IEnumerable<float> FloatRange(float min, float max, float step)
{
    for (int i = 0; i < int.MaxValue; i++)
    {
        float value = min + step * i;
        if (value > max)
        {
            break;
        }
        yield return value;
    }
}

In MiscUtil I have some range code which does funky stuff thanks to Marc Gravell's generic operator stuff, allowing you:

foreach (float x in 10f.To(20f).Step(0.1f))
{
    ...
}
Jon Skeet
Thanks Jon. Just curious about a built-in version. :-)
Mau
Don't use addition, use multiplication for better precision.
liori
If you want to ensure that you'll hit `max` in the range you'll need an approximate comparison to `max` in the for loop instead of just `<=`. Repeated additions could have you end up slightly higher than the given `max` value. Alternatively you could increment until you're one step less than max and `yield return max;` at the end.
Ron Warholic
i think comment should be like this "Very very thanks ! Dear jon "
steven spielberg
@liori: Edited.
Jon Skeet
@Ron: Yes, you could end up being slightly higher than the given max value - in which case `max` wouldn't be returned, but you'll still terminate. If you want to absolutely guarantee that `max` is returned, you would need to change it, I agree.
Jon Skeet
+2  A: 

You could do

Enumerable.Range(100, 100).Select(i => i / 10F)

But it isn't very descriptive.

Yuriy Faktorovich
Nice actually. Short, it works and it's built-in.
Mau