Use fabs() (in math.h) to get absolute-value for double:
double d1 = fabs(-3.8951);
Answer from herohuyongtao on Stack OverflowVideos
I am writing a #![no_std] library that at one point needs to get the absolute value of a floating point number. This seems to need the standard library though. Currently I use #[cfg(feature = ...)] conditionals to enable a custom implementation of abs when the std feature is disabled, but this compiles to longer assembly compared to the std abs: https://godbolt.org/z/jY115ebTv. Is there a way to get this code quality in #![no_std]?
EDIT: I have compiled all answers in the thread in this godbolt link: https://godbolt.org/z/9nEEMofEG.
EDIT: Same code on the rust playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=02e74329c1fcc999e55f850c0544528b.
FINAL EDIT: For those who do not wish to read the whole thread, the code I ended up using is a combination of the comment by u/boomshroom and notes by u/matthieum:
fn abs(x: f64) -> f64 {
f64::from_bits(x.to_bits() & !(1 << 63))
}This compiles to the same single assembly instruction (andps) as the std abs on x86_64, which is all that's relevant for me. I have not tested other targets.