package main
import (
"fmt"
)
/*
==================================================
Title: Reusable Floating-Point Range Function
==================================================
This function:
- Validates inputs
- Returns a slice of float64 values
- Uses integer-controlled iteration
- Avoids cumulative floating-point errors
*/
func GenerateRange(
start float64,
end float64,
step float64,
) ([]float64, error) {
// Validate input arguments.
if step <= 0 {
return nil, fmt.Errorf("step must be positive")
}
if end < start {
return nil, fmt.Errorf(
"end must be greater than or equal to start",
)
}
/*
Determine how many values are needed.
Example:
start = 0.0
end = 1.0
step = 0.1
count = 11
*/
count := int((end-start)/step) + 1
// Preallocate capacity to avoid reallocations.
values := make([]float64, 0, count)
for i := 0; i < count; i++ {
// Calculate the value from the index.
value := start + float64(i)*step
values = append(values, value)
}
return values, nil
}
func main() {
values, err := GenerateRange(0.0, 1.0, 0.1)
if err != nil {
fmt.Println(err)
return
}
for _, value := range values {
fmt.Printf("%.1f\n", value)
}
}
/*
run:
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0
*/