<jupyter_start><jupyter_text>`numpy.arange()` with floats considered harmfulA few examples used in this notebook are taken from http://quantumwise.com/forum/index.php?topic=110.0.VIVgyIctjRZ.We often need series of regularly spaced numbers. [numpy.arange()](https://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html) is great for that, as long as the step size is an integer.If the step size is a floating-point number, however, the result might not be what you expect.<jupyter_code>import numpy as np<jupyter_output><empty_output><jupyter_text>But when I last tried it worked as expected ...[numpy.arange()](https://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html) is NumPy's extension of Python's built-in [range()](https://docs.python.org/3/library/functions.htmlfunc-range) function.The latter only works with integers, which are also no problem for the former:<jupyter_code>np.arange(7)  # defaults: start=0, step=1
np.arange(1, 7)
np.arange(1, 7, 2)
np.arange(1, 7, 6)<jupyter_output><empty_output><jupyter_text>The `start` value is always part of the returned range, the `stop` value is never part of it.Contrary to `range()`, `numpy.arange()` also works with floating-point numbers.<jupyter_code>np.arange(0.4, 1.1, 0.1)<jupyter_output><empty_output><jupyter_text>Also here, as expected, the `stop` value is not part of the range.  So what's the problem?The problem is that some numbers (infinitely many, actually) cannot be represented exactly as fixed-size binary floating-point numbers. Doing calculations with floating-point numbers will often lead to rounding errors. And exactly those rounding errors may lead to unexpected results.For example here:<jupyter_code>np.arange(0.5, 1.1, 0.1)<jupyter_output><empty_output><jupyter_text>Wow, now `stop` is suddenly included in the range! We didn't expect that!That's the reason why care has to be taken when using `np.arange()` with floating-point numbers.  OK, I see the problem now, but what's the solution?Well, there isn't a single solution for all use cases, it depends on what you need.If you know the first and the last value that should be in your range and the total number of values, you should use [numpy.linspace()](https://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html).<jupyter_code>np.linspace(0.5, 1.1, 7)<jupyter_output><empty_output><jupyter_text>In contrast to `np.arange()`, the resulting range includes the last value.If you want it to exclude the last value, you can use the `endpoint` argument (and reduce the number of values by 1).<jupyter_code>np.linspace(0.5, 1.1, 6, endpoint=False)<jupyter_output><empty_output><jupyter_text>If you, however, want to create a range with a given *spacing*, you'd have to manually calculate the *number of values* before being able to use `numpy.linspace()`.It would be great if there were a feature of either `numpy.linspace()` or `numpy.arange()` that would allow specifying a *spacing* but would also avoid the above-mentioned problem.This was discussed [years ago on the NumPy mailing list](https://mail.python.org/pipermail/numpy-discussion/2007-September/029129.html). Sadly, nobody could come up with a good solution.So for now, you're stuck with adding or subtracting small amounts to/from the `stop` value to get the desired behavior.<jupyter_code>step = 0.1
np.arange(0.5, 1.1 - step*0.5, step)<jupyter_output><empty_output><jupyter_text>This yields the expected result, but it only works if you know that the distance between `start` and `stop` is (approximately) an integer multiple of the spacing.<jupyter_code>assert np.isclose((1.1 - 0.5) % step, 0.0)<jupyter_output><empty_output><jupyter_text>If you want to include the `stop` value, you can do something like this:<jupyter_code>np.arange(0.5, 1.1 + step*0.5, step)<jupyter_output><empty_output><jupyter_text>Again, you have to make sure that the spacing fits to the distance:<jupyter_code>assert np.isclose((1.1 + 0.5) % step, 0.0)<jupyter_output><empty_output><jupyter_text>Can't this be done automatically?Well, let's try ...<jupyter_code>def myrange(start, stop, step=1):
    # Don't use this function, see below!
    return np.arange(start, stop - step*0.5, step)
myrange(0.5, 1.1, 0.1)<jupyter_output><empty_output><jupyter_text>OK, the problematic case from above works. But let's change the `stop` value a little bit:<jupyter_code>myrange(0.5, 1.11, 0.1)<jupyter_output><empty_output><jupyter_text>Here, we would expect `1.1` to be part of the range, because it's clearly smaller than `1.11`. So let's modify our function:<jupyter_code>def myrange(start, stop, step=1):
    if np.isclose((stop - start) % step, 0.0):
        stop -= step * 0.5
    return np.arange(start, stop, step)
myrange(0.5, 1.11, 0.1)<jupyter_output><empty_output><jupyter_text>OK, now `1.1` is part of the range, as expected.<jupyter_code>myrange(0.5, 1.1, 0.1)<jupyter_output><empty_output><jupyter_text>The previous example still works. Good.This isn't a very elegant solution, though. The behavior depends on the tolerances used in [numpy.isclose()](https://docs.scipy.org/doc/numpy/reference/generated/numpy.isclose.html), namely `rtol` and `atol`. Let's add those to our function!<jupyter_code>def myrange(start, stop, step=1, dtype=None, **kwargs):
    if np.isclose((stop - start) % step, 0.0, **kwargs):
        stop -= step * 0.5
    return np.arange(start, stop, step, dtype)<jupyter_output><empty_output><jupyter_text>Note that we also enabled the `dtype` argument from `numpy.arange()`.<jupyter_code>myrange(0.5, 1.11, 0.1)
myrange(0.5, 1.11, 0.1, atol=0.02)<jupyter_output><empty_output><jupyter_text>This is a quite constructed example, but it should show that setting the tolerance worksOne difference to `numpy.arange()` is that even when only passing integers, the result consists of floating-point numbers.<jupyter_code>myrange(1, 7)<jupyter_output><empty_output><jupyter_text>We could add this as branch to our function implementation, but I think it isn't that important. And if we really want integers, we can still force them with `dtype`:<jupyter_code>myrange(1, 7, dtype=int)<jupyter_output><empty_output><jupyter_text>OK, that doesn't look that bad, does it?  But what if I want to include the endpoint?OK, you're right. Sometimes, we want the endpoint to be included, so let's try to add this as an option.<jupyter_code>def myrange(start, stop, step=1, endpoint=False, dtype=None, **kwargs):
    # Don't use this function, see below!
    if np.isclose((stop - start) % step, 0.0, **kwargs):
        if endpoint:
            stop += step * 0.5
        else:
            stop -= step * 0.5
    return np.arange(start, stop, step, dtype)
myrange(0.5, 1.1, 0.1, endpoint=True)<jupyter_output><empty_output><jupyter_text>OK, this seems to work. Let's try another example ...<jupyter_code>myrange(1, 2, 0.2, endpoint=True)<jupyter_output><empty_output><jupyter_text>What? The endpoint clearly isn't part of the range!The problem is that we check if the result of the modulus operator (`%`) is close to `0.0`, but we should also check the case where it is close to `step`!We should try to add this check:<jupyter_code>def myrange(start, stop, step=1, endpoint=False, dtype=None, **kwargs):
    # Don't use this function, see below!
    remainder = (stop - start) % step
    if np.any(np.isclose(remainder, (0.0, step), **kwargs)):
        if endpoint:
            stop += step * 0.5
        else:
            stop -= step * 0.5
    return np.arange(start, stop, step, dtype)
myrange(1, 2, 0.2, endpoint=True)<jupyter_output><empty_output><jupyter_text>Good, that's settled. Let's try another one:<jupyter_code>myrange(0.5, 1.11, 0.1, endpoint=True)<jupyter_output><empty_output><jupyter_text>Now this is a little strange, because `1.11` is not included. But on the other hand, it isn't even part of the series!As far as I can tell, the argument `endpoint` only really makes sense for integer multiples.For now, I don't know a better solution than to just disallow this case.<jupyter_code>def myrange(start, stop, step=1, endpoint=False, dtype=None, **kwargs):
    remainder = (stop - start) % step
    if np.any(np.isclose(remainder, (0.0, step), **kwargs)):
        if endpoint:
            stop += step * 0.5
        else:
            stop -= step * 0.5
    elif endpoint:
        raise ValueError("Invalid stop value for endpoint=True")
    return np.arange(start, stop, step, dtype)
myrange(0.5, 1.1, 0.1, endpoint=True)
myrange(0.5, 1.11, 0.1, endpoint=True)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1177574478067089, 'fraction_numerical': 0.023692235514895615, 'mean_word_length': 4.888812154696133, 'pattern_counts': {'":': 0, '<': 93, '<?xml version=': 0, '>': 93, 'https://': 6, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '23', 'dir': 'jupyter-structured-clean-dedup', 'id': '268576', 'license': 'CC0-1.0', 'n_tokens_mistral': 2947, 'n_tokens_neox': 2791, 'n_words': 936, 'path': 'misc/arange.ipynb', 'repo_name': 'mgeier/python-audio', 'size': '8526'}