Here's a Go implementation of numpy's linspace functionality using only the math package:
package main
import (
"fmt"
"math"
)
// Linspace generates num evenly spaced values between start and stop (inclusive)
func Linspace(start, stop float64, num int) []float64 {
if num < 0 {
return []float64{}
}
if num == 0 {
return []float64{}
}
if num == 1 {
return []float64{start}
}
result := make([]float64, num)
step := (stop - start) / float64(num-1)
for i := 0; i < num; i++ {
result[i] = start + float64(i)*step
}
// Ensure the last value is exactly stop (to avoid floating point errors)
result[num-1] = stop
return result
}
// LinspaceExcludeEnd generates num evenly spaced values between start and stop (excluding stop)
func LinspaceExcludeEnd(start, stop float64, num int) []float64 {
if num <= 0 {
return []float64{}
}
result := make([]float64, num)
step := (stop - start) / float64(num)
for i := 0; i < num; i++ {
result[i] = start + float64(i)*step
}
return result
}
func main() {
// Example usage - equivalent to np.linspace(0, 10, 5)
values := Linspace(0, 10, 5)
fmt.Println("Linspace(0, 10, 5):", values)
// Example with negative range
values2 := Linspace(-5, 5, 11)
fmt.Println("Linspace(-5, 5, 11):", values2)
// Example excluding endpoint
values3 := LinspaceExcludeEnd(0, 10, 5)
fmt.Println("LinspaceExcludeEnd(0, 10, 5):", values3)
// Example with math functions
// Create linspace from 0 to 2π
angles := Linspace(0, 2*math.Pi, 9)
fmt.Println("\nAngles from 0 to 2π:")
for i, angle := range angles {
fmt.Printf(" angles[%d] = %.4f (sin=%.4f, cos=%.4f)\n",
i, angle, math.Sin(angle), math.Cos(angle))
}
}
This implementation provides two functions:
Linspace(start, stop, num) - Creates num evenly spaced values from start to stop (inclusive), matching numpy's default behavior
LinspaceExcludeEnd(start, stop, num) - Creates num evenly spaced values from start up to but not including stop (equivalent to numpy's endpoint=False)
The key features:
- Handles edge cases (num <= 0, num == 1)
- Ensures the last value is exactly
stop to avoid floating-point rounding errors
- Returns an empty slice for invalid inputs
- Works with negative ranges and decimal values
The example demonstrates various use cases including creating angles for trigonometric calculations, which is a common use of linspace in scientific computing.