Finding absolute value of a number without using Math.abs()

后端 未结 10 1539
轮回少年
轮回少年 2021-02-02 11:16

Is there any way to find the absolute value of a number without using the Math.abs() method in java.

相关标签:
10条回答
  • 2021-02-02 12:15

    Like this:

    if (number < 0) {
        number *= -1;
    }
    
    0 讨论(0)
  • 2021-02-02 12:16

    Yes:

    abs_number = (number < 0) ? -number : number;
    

    For integers, this works fine (except for Integer.MIN_VALUE, whose absolute value cannot be represented as an int).

    For floating-point numbers, things are more subtle. For example, this method -- and all other methods posted thus far -- won't handle the negative zero correctly.

    To avoid having to deal with such subtleties yourself, my advice would be to stick to Math.abs().

    0 讨论(0)
  • 2021-02-02 12:17

    If you look inside Math.abs you can probably find the best answer:

    Eg, for floats:

        /*
         * Returns the absolute value of a {@code float} value.
         * If the argument is not negative, the argument is returned.
         * If the argument is negative, the negation of the argument is returned.
         * Special cases:
         * <ul><li>If the argument is positive zero or negative zero, the
         * result is positive zero.
         * <li>If the argument is infinite, the result is positive infinity.
         * <li>If the argument is NaN, the result is NaN.</ul>
         * In other words, the result is the same as the value of the expression:
         * <p>{@code Float.intBitsToFloat(0x7fffffff & Float.floatToIntBits(a))}
         *
         * @param   a   the argument whose absolute value is to be determined
         * @return  the absolute value of the argument.
         */
        public static float abs(float a) {
            return (a <= 0.0F) ? 0.0F - a : a;
        }
    
    0 讨论(0)
  • 2021-02-02 12:21

    Although this shouldn't be a bottle neck as branching issues on modern processors isn't normally a problem, but in the case of integers you could go for a branch-less solution as outlined here: http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs.

    (x + (x >> 31)) ^ (x >> 31);
    

    This does fail in the obvious case of Integer.MIN_VALUE however, so this is a use at your own risk solution.

    0 讨论(0)
提交回复
热议问题