/*
==================================================
Title: Reusable Floating-Point Range Function
==================================================
This implementation:
- Validates inputs
- Returns a Vec<f64>
- Uses integer-controlled iteration
- Avoids cumulative floating-point errors
*/
fn generate_range(
start: f64,
end: f64,
step: f64,
) -> Result<Vec<f64>, String> {
// Validate arguments.
if step <= 0.0 {
return Err(
"step must be greater than zero".to_string()
);
}
if end < start {
return Err(
"end must be greater than or equal to start"
.to_string()
);
}
// Calculate the required number of values.
let count: usize =
((end - start) / step).floor() as usize + 1;
// Allocate the Vec with the final size in mind.
let mut values: Vec<f64> =
Vec::with_capacity(count);
for i in 0..count {
let value: f64 = start + (i as f64 * step);
values.push(value);
}
Ok(values)
}
fn main() {
match generate_range(0.0, 1.0, 0.1) {
Ok(values) => {
for value in values {
println!("{:.1}", value);
}
}
Err(error) => {
eprintln!("Error: {}", error);
}
}
}
/*
run:
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0
*/