nluigi - 10 months ago 54

Python Question

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

where`a`

`c`

`n`

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

`[a,b]`

`a<b<c`

`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?

Answer Source

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)
```

Plotting:

```
from matplotlib import pyplot as plt
fig, ax = plt.subplots(1, 1)
ax.eventplot(pts)
ax.margins(x=0.05)
```

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)`

.