How to generate a range of floating-point numbers in Rust

3 Answers

0 votes
fn main() {
    /*
    ==================================================
    Title: Generate a Range of Floating-Point Numbers
    ==================================================

    Best Practice:
    - Use an integer loop counter.
    - Compute each floating-point value from the index.
    - Avoid repeatedly adding the step value because
      floating-point rounding errors can accumulate.
    */

    let start: f64 = 0.0;
    let step: f64 = 0.1;
    let count: usize = 11; // Generates 0.0 through 1.0 inclusive.

    /*
    Use an integer-controlled loop.

    Each value is calculated independently:

        start + index * step

    This avoids accumulated rounding error from:

        value += step
    */
    for i in 0..count {
        let value: f64 = start + (i as f64 * step);

        // Display one decimal place.
        println!("{:.1}", value);
    }
}


/*
run:

0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0


*/

 



answered Oct 7 by avibootz
0 votes
/*
==================================================
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

*/

 



answered Oct 7 by avibootz
0 votes
fn main() {
    /*
    ==================================================
    Title: Iterator-Based Floating-Point Range
    ==================================================

    Rust's iterators provide a clean and efficient way
    to generate values while still using integer indices.
    */

    let start: f64 = 0.0;
    let step: f64 = 0.1;
    let count: usize = 11;

    let values = (0..count)
        .map(|i| start + (i as f64 * step));

    for value in values {
        println!("{:.1}", value);
    }
}


/*
run:

0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0

*/

 



answered Oct 7 by avibootz
...