Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 497
Theja Avatar asked Jun 13 '12 10:06

Theja


People also ask

How do you do absolute value without abs in Python?

Python Absolute Value Without ABS You can use if-else ladder to print the positive value only for the number as that is also the the task that complex number do but it may not work with complex number.

How do you find the absolute value of a number?

The absolute value (or modulus) | x | of a real number x is the non-negative value of x without regard to its sign. For example, the absolute value of 5 is 5, and the absolute value of −5 is also 5. The absolute value of a number may be thought of as its distance from zero along real number line.

How do you find the absolute value of a number in Java?

abs(int a) 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.

Which of the following methods returns the absolute value of a number?

abs() function returns the absolute value of a number.


1 Answers

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;     } 
like image 57
mihaisimi Avatar answered Oct 07 '22 11:10

mihaisimi