nluigi nluigi - 1 month ago 7
Python Question

Numpy - generating a sequence with a higher resolution within certain bounds

Generating a sequence of a range with evenly spaced points using Numpy is accomplished easily using

is the start of the range,
is the endpoint of the range and
are the number of evenly spaced intervals.

I am interested to know if there is any similar function which allows a finer resolution for a subset of the range e.g.
. At the moment i am using:

np.append(np.linspace(a, b, n), np.linspace(b, c, n))

which does the trick but is there a Numpy implementation already specifically for this or perhaps a smarter way to do this?


You could construct such a sequence by first making an array containing the spacings between each pair of points, then taking a cumsum over this.

For example, let's suppose I want to go from 0 to 50 everywhere in steps of 1, except between 20 and 30 where I want steps of 0.25:

import numpy as np

deltas = np.repeat([0, 1, 0.25, 1], [1, 20, 40, 20])
pts = np.cumsum(deltas)


from matplotlib import pyplot as plt

fig, ax = plt.subplots(1, 1)

enter image description here


I'd totally forgotten about np.r_, which offers a very nice compact way to achieve the same thing:

pts2 = np.r_[0:20:1, 20:30:0.25, 30:51:1]

As well as specifying a step size manually, you can also use an imaginary number as the step size, which is equivalent to using np.linspace to specifying the number of steps to take, e.g. np.r_[0:10:20j] is the same as np.linspace(0, 10, 20).