You can find the absolute value without using “ABS” with the simple method below.
First compute the square of the number. Then calculate the square root of the calculated value.
Example 1: Simple way
1 2 3 4 5 6 7 | number = -10 abs_number = (number**2)**0.5 print(number) print(abs_number) |
Example 2: Create your custom abs method.
1 2 3 4 5 6 7 8 9 10 | def custom_abs(value): return (value**2)**(0.5) number =-20 print(number) print(custom_abs(number)) |
Example 3: Alternative way.
1 2 3 4 5 6 7 | number1 =-50 number2 = number1 * ((number1>0) - (number1<0)) output = " {0} {1}".format(number2,number1) print(output) |
Example 4:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | # Python3 implementation of above approach CHARBIT = 8; SIZE_INT = 8; # This function will return # absolute value of n def getAbs(n): mask = n >> (SIZE_INT * CHARBIT - 1); return ((n + mask) ^ mask); # Driver Code n = -6; print("Absolute value of",n,"is",getAbs(n)); # This code is contributed by mits |