I would like to know how to do a abs max in Rust and return the value with the sign.
fn main() {
let ts: Vec<f32> = vec![10.0, 20.0, -30.0];
let abs_max = ts.iter().fold(f32::NAN, |a, &b| (a.abs()).max(b.abs()));
println!("{}", abs_max);
}
I want the result to be -30.0 in this case. But I am getting 30.0. Can the experts here help me to get an performance optimised snippet?
Also, assume there wont be any NAN in my ts.
This is a simple example. But what I need ultimately is the abs mean of the vec but the sign should be from the abs max..
let abs_max = -30.0
let abs_max_sign = abs_max.signum();
let abs_mean = YY;
let signed_abs_mean = YY * abs_max_sign;
return signed_abs_mean;
Thanks!.
Is it possible to check it there are more than 2 elements? Because it fails when I have one element in my vec. Is there any better alternative than using if condition