A simple question about floating point addition

hello forum, simple question why i cannot reach one in this simple loop ?
thx Julien.

fn main() {
    let mut ct: f32 = 0.0;
    while ct <= 1.0 {
        print!("-->{}\n", ct);
        ct += 0.1;
    }
}

(Playground)

Output:

-->0
-->0.1
-->0.2
-->0.3
-->0.4
-->0.5
-->0.6
-->0.70000005
-->0.8000001
-->0.9000001

Errors:

   Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 1.70s
     Running `target/debug/playground`

Roundoff error. If you step by an integer times a power of two it will work as you'd expect, e.g. stepping by 0.125.

The same thing happens in any programming language, BTW.

3 Likes

https://stackoverflow.com/questions/588004/is-floating-point-math-broken/588014

2 Likes

thanks ^^
quick overview:

"What Every Computer Scientist Should Know About Floating-Point Arithmetic" :

1 Like

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.