简体   繁体   中英

How do I do something like numpy's arange in Go?

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM