How to idiomatically find absmax()?

Hi All,

Can you please suggest a simple solution for finding an absolute max but the result is with sign?

fn main() {
    let a = f32::NAN;
    let b = 10.0f32;
    let c = -11.0f32;
    let d = 12.0f32;
    
    println!("Expected:  10.0f, when comparing a.absmax(b)");
    println!("Expected: -11.0f, when comparing b.absmax(c)");
    println!("Expected:  12.0f, when comparing c.absmax(d)");
    println!("Expected: -11.0f, when comparing a.absmax(c)");
}

I wrote a fn like below and is there any simple alternative?

fn absmax(a: f32,b: f32) -> f32 {
   match a.abs().max(b.abs()) {
       v if v.abs() == a.abs() => a,
       v if v.abs() == b.abs() => b,
       _                 => 0.0,
   }
}

Why not just if a.abs() > b.abs() { a } else { b }

1 Like

For some reason when I tried earlier it was showing f32::NAN, when any one of the element is f32::NAN. It works now. Thanks :slight_smile:

If either argument is NaN, then the comparison will evaluate to false and the result will be b. So this version will return NaN if b is NaN. If you want different behavior, you will need to add an explicit is_nan check.

1 Like