No sane way to generate [1., 1.5, 2., 2.5].iter().cloned()...?

Stumbled onto this old post.

Really? This works:

#[test]
fn t() {
    assert_eq!(
        (2..=5).map(|x| (x as f32) / 2.0).collect::<Vec<_>>(),
        [1., 1.5, 2., 2.5],
    );
}

Maybe this is "insane"? Idk seems pretty standard to me.

TL;DR yes: iterate integers and then map to floating point, which avoids the pitfalls of accumulating floating point error.

(Generally points about using Rust rather than evolving Rust/std should go on the users forum)

3 Likes

The example given is probably deliberately simple; I know I would be much happier reviewing this code if the endpoints were made explicit. And I'd be significantly happier modifying the code.

I don't know if this functionality should be overly supported in the standard library, mostly because most of the time I expect people want some variant of linspace, or at least some extra control around what exactly the endpoints are and exactly how floating point is going to be treated.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.