Vector.range constructor
Creates a Vector with values in the specified range, incremented by the specified step size.
end: End value (exclusive). Can be int or double.
start: Start value. Default is 0. Can be int or double.
step: Step size. Default is 1. Can be positive or negative.
Example:
print(Vector.range(6, start: 1, step: 2));
// Output: [ 1, 3, 5 ]
print(Vector.range(0, start: 5, step: -1));
// Output: [ 5, 4, 3, 2, 1 ]
Implementation
factory Vector.range(num end, {num start = 0, num step = 1}) {
if (step == 0) {
throw ArgumentError('Step size cannot be zero');
}
// Validate bounds for positive steps
if (step > 0 && start >= end) {
throw ArgumentError('Start must be less than end when step is positive');
}
// Validate bounds for negative steps
if (step < 0 && start <= end) {
throw ArgumentError(
'Start must be greater than end when step is negative');
}
// Calculate the total number of elements upfront to avoid floating-point loop drift.
// .ceil() guarantees we stop just before the 'end' value.
int count = ((end - start) / step).ceil();
// Explicitly define the list type for better performance
List<Complex> range = [];
for (int i = 0; i < count; i++) {
// Calculate the exact value using multiplication instead of repeated addition
num value = start + (i * step);
range.add(Complex(value));
}
return Vector.fromList(range);
}