Reputation: 2310
Numpy's arange function returns a list of evenly spaced values within a given interval with float steps. Is there a short and simple way to create a slice like that in Go?
Upvotes: 2
Views: 2575
Reputation: 4231
Based on val's solution, I would suggest to avoid using "x+=step" because depending on the limits and the step, rounding errors will accumulate and you may leave the last value undefined or even worse, try to define the N+1 value, causing a panic.
This could be solved with:
func arange2(start, stop, step float64) []float64 {
N := int(math.Ceil((stop - start) / step))
rnge := make([]float64, N)
for x := range rnge {
rnge[x] = start + step*float64(x)
}
return rnge
}
http://play.golang.org/p/U67abBaBbv
Upvotes: 5
Reputation: 8689
None that I am aware of. You can define your own though:
import "math"
func arange(start, stop, step float64) []float64 {
N := int(math.Ceil((stop - start) / step));
rnge := make([]float64, N, N)
i := 0
for x := start; x < stop; x += step {
rnge[i] = x;
i += 1
}
return rnge
}
which returns:
arange(0., 10., 0.5)
[0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6 6.5 7 7.5 8 8.5 9 9.5]
Corresponding to the Python:
>>> np.arange(0., 10., 0.5)
array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. ,
5.5, 6. , 6.5, 7. , 7.5, 8. , 8.5, 9. , 9.5])
Note that because of the way I defined the iteration, you cannot use negative steps in my simple Go version, but you can define something a bit more robust if you need to.
Upvotes: 3