Re:One does not simply calculate the absolute value
by Sharlin on Sunday August 22, 2021 @06:01PM
(#28270082)
Computing the absolute value of a signed (fixed-size, two's complement) integer is not trivial either, because there is no positive i such that `abs(INT_MIN) == i`. Some languages like Java just give you `abs(INT_MIN) == INT_MIN` because:
where ~ is the bitwise complement. Even worse, in C and C++ specifically, because overflow of signed integers is undefined behavior, so is `abs(INT_MIN)`! To be able to represent the absolute value, you need to either return the corresponding unsigned type (if your language has them), promote to a wider type, or return a tuple `(carry_bit, result)`.
[ Parent
| on HN ]
Re:One does not simply calculate the absolute value
by nightcracker on Monday August 23, 2021 @01:41AM
(#28272645)
This is why Rust has `abs`, `checked_abs`, `wrapping_abs`, `overflowing_abs`, `saturating_abs` and `unsigned_abs`.
Checked returns a Result enum that is an error on overflow, wrapping silently wraps (as in your answer), overflowing wraps but has a boolean indicator whether a wrap has occurred, saturating bounds at the types limits rather than wrapping and unsigned abs always gives the correct result albeit as a different type.
The unqualified abs panics on overflow on debug but silently wraps on release mode, like all Rust arithmetic code does by default.