Forma alternativa a Math.abs

Olá gente, tô precisando calcular o valor absoluto de uma expressão, mas não posso usar o método Math.abs. O código está assim:

static double raizQuadrada(double a, double epsilon) {
double b;
double bAnterior;
b = a/2;
bAnterior = 0;
if (a > 0 && epsilon > 0 && epsilon < 1) {
while (Math.abs(b - bAnterior) >= epsilon) {
bAnterior = b;
b = (bAnterior + (a / bAnterior)) * 1 / 2;
}
return (b);
}

Preciso achar o valor absoluto de b - bAnterior sem usar o Math.abs. Alguém pode me dar uma sugestão do que fazer?

De acordo com:

Returns the absolute value of an int value. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned.

Note that if the argument is equal to the value of Integer.MIN_VALUE , the most negative representable int value, the result is that same value, which is negative.

Você pode fazer assim:

public int abs(int a) {
    return (a < 0) ? -a : a;
}

FONTE: Math.html#abs-int

1 curtida