Answer the question
In order to leave comments, you need to log in
How to compare two real numbers without if?
Actually, you need to compare two numbers without using conditional operators and comparison operations. Language - Java.
There are no problems for integers, everything is done in one line. Problems begin if the numbers are real. In general, my algorithm is this: subtract one number from another and look at the sign of the resulting expression. But this won't work for doubles, since the sign can be obtained by shift operations, which are only defined for integers. it is also impossible to lead to a whole, because if the difference between the numbers is less than one, then the algorithm will not work correctly. Came up with this trick:
public class Compare {
public static int cmp(double a, double b) {
double r = a - b, d = 0;
int i = 19;
while (i != 0 && d == 0) {
r *= 10;
d = (int)r % 10;
i--;
}
return ((int)d >> 63) + 1;
}
}
public class Compare {
public static int cmp(double a, double b) {
return (int)((Double.doubleToRawLongBits(a - b)) >> 63) + 1;
}
}
Answer the question
In order to leave comments, you need to log in
Math.abs(a-b)/(a-b)
This is without taking into account the equality of numbers. The abs library method is translated into the fabs fpu command. No comparisons.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question