Forma alternativa a Math.abs

1 resposta
java
J

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?

1 Resposta

Lucas_Camara

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

Criado 6 de maio de 2020
Ultima resposta 6 de mai. de 2020
Respostas 1
Participantes 2