Addev
Addev

Reputation: 32233

Java: Max and Min in absolute value

I'm looking for a method that given 2 floats A and B return the value (A or B) with lower absolute value.

Initially I tried

Math.min(Math.abs(A),Math.abs(B)); 

but it is not correct because for example for (-9,-2) return +2 and the return value I'm looking for is -2.

Is there some native/built-in for that?

Upvotes: 3

Views: 6313

Answers (5)

Fritz
Fritz

Reputation: 10055

Well, it's a correct behaviour.

You're getting the absolute value of both numbers inside the Min funcion which returns the minimum value of both. In your case that's 2 because you're comparing 9 and 2.

EDIT

AFAIK There's not built-in way to do what you want to do. As others have suggested, you have to make the comparation yourself with something like:

Math.abs(A) < Math.abs(B) ? A : B

Just remember to be careful with the types you compare and the result.

Upvotes: 2

Edd
Edd

Reputation: 3822

Math.min() returns the lowest of the two parameters passed into it. In the example above, you're providing it with arguments of 999 and 2 (The absolute values generated by Math.abs().

You could replace the Math.min() call with something like:

Math.abs(A) < Math.abs(B) ? A : B;

Upvotes: 5

Michael Lorton
Michael Lorton

Reputation: 44386

I don't approve of using upper-case for local variables, but

 (Math.abs(A) < Math.abs(B)) ? A : B

Upvotes: 7

Nate
Nate

Reputation: 1921

val = (Math.abs(A) < Math.abs(B)) ? A : B; 

Upvotes: 4

Sean Owen
Sean Owen

Reputation: 66886

Math.abs(A) < Math.abs(B) ? A : B;

Upvotes: 11

Related Questions