0

I just came across the problem that I could not use the built-in range() function of python for float values. So I decided to use a float-range function that I manually defined:

def float_range(start, stop, step):
    r = start
    while r < stop:
        yield r
        r += step

Problem is: This function returns a generator object. Now I needed this range for a plot:

ax.hist(some_vals, bins=(float_range(some_start, some_stop, some_step)), normed=False)

This will not work due to the return type of float_range(), which is a generator, and this is not accepted by the hist() function. Is there any workaround for me except not using yield?

4
  • Why is not using yield a "workaround"? What did you hope to gain by using yield? Commented Jun 2, 2014 at 7:34
  • What does bins expect? An integer? or a range? Commented Jun 2, 2014 at 7:35
  • 1
    yield is the standard solution for defining a default range function. Commented Jun 2, 2014 at 7:35
  • @Christian an int OR range Commented Jun 2, 2014 at 7:36

2 Answers 2

3

If you need to give a range, you can do either

ax.hist(some_vals, bins=(list(float_range(some_start, some_stop, some_step))), normed=False)

Or just make your float_range return a list:

def float_range(start, stop, step):
    result = []
    r = start
    while r < stop:
        result.append(r)
        r += step
    return result

BTW: nice reference on what you can do with generators in Python: https://wiki.python.org/moin/Generators

Sign up to request clarification or add additional context in comments.

1 Comment

that list()-thing is what I was looking for, thank you!
1

You can convert a generator to a list using:

list(float_range(1, 4, 0.1))

But seeing you are using matplotlib, you should be using numpy's solution instead:

np.arange(1, 4, 1, dtype=np.float64)

or:

np.linspace(start, stop, (start-stop)/step)

4 Comments

but with np.arange I could not get any float values to work, like np.arange(0.2, 0.8, 0.05)
NumPy's solution is linspace. It is specifically warned that using arange for non-integer steps is a bad idea in the documentation.
@ZerO you can force it to give you floats.
@user2357112 using arange with floats may lead to numerical inaccuracies, and so not give you exactly what you want; but the OP will have the same problem with the proposed approach. Using one or the other depends on what do you want to ensure are correct: distance or number of elements. For the bins of a plot, probably either would work fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.