Strange comparison behavior

โš“ Rust    ๐Ÿ“… 2025-11-10    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 5      

surdeus

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Strange comparison behavior

Hi everyone,
I'm a student working on a small Rust project with a lookup table. I wrote a simple linear search function that, given a xq and a monotonic axis array, returns the interval indices (i0,i1) where xq lies. I also wanted to return (i,i) if xq is exactly equal to a breakpoint.

Here's a simplified version of my function:

fn index_search<T: FloatLike, const N: usize>(xq: &T, axis: &[T;N])-> (usize,usize){
    if *xq<=axis[0] {
        return (0,0);
    }
    if *xq>=axis[N-1] {
        return (N-1, N-1);
    }
    for i in 0..N-1 {
        let x0 = axis[i];
        let x1 = axis[i+1];
        if *xq==x0 {
            return (i, i);
        }
        if *xq>=x0 && *xq<=x1 {
            return (i, i+1);
        }
    }
    return (0,0)
}

The strange thing is: when I search for a value that exactly matches a breakpoint, it doesn't return (i,i) as expected.
Interestingly, if I change the interval check from >=/<= to >/<, the function works as intended.
I donยดt fully understand why. Logically, if xq==x0, the first branch should return (i,i) before even reaching the interval check, right?

I know it might be a silly question, I'm still learning Rust but I'd love to understand why the original version behave differently and whether this is something about floating-point comparisons or Rust control flow.

Thanks a lot in advance for any explanations!

2 posts - 2 participants

Read full topic

๐Ÿท๏ธ Rust_feed