Puzzling behaviour incrementing an f64

Can anyone explain what I am doing wrong here?

fn main() {

    let mut x: f64 = 3.55;
    let mut rvec = vec![x];

    for _ in 0..30 {
    
        x += 0.01;
        rvec.push(x);
        
    }

    dbg!(rvec);
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.51s
     Running `target/debug/playground`
[src/main.rs:13:5] rvec = [
    3.55,
    3.5599999999999996,
    3.5699999999999994,
    3.579999999999999,
    3.589999999999999,
    3.5999999999999988,
    3.6099999999999985,
    3.6199999999999983,
    3.629999999999998,
    3.639999999999998,
    3.6499999999999977,
    3.6599999999999975,
    3.6699999999999973,
    3.679999999999997,
    3.689999999999997,
    3.6999999999999966,
    3.7099999999999964,
    3.719999999999996,
    3.729999999999996,
    3.7399999999999958,
    3.7499999999999956,
    3.7599999999999953,
    3.769999999999995,
    3.779999999999995,
    3.7899999999999947,
    3.7999999999999945,
    3.8099999999999943,
    3.819999999999994,
    3.829999999999994,
    3.8399999999999936,
    3.8499999999999934,
]

Nothing. If you want to know why the printed values are not round, that's because floats aren't decimals, they are binary.

3 Likes

Alternatively, here's a video explaining what's going on: https://youtu.be/PZRI1IfStY0?si=EvupjapKwNCc1NZc

1 Like

Thank You, this link you provided explains it very well

A more approachable explanation: https://floating-point-gui.de/

2 Likes

Thank you, this helps a lot

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.