A
A
Andrey Yanduganov2016-09-08 14:36:53
Java
Andrey Yanduganov, 2016-09-08 14:36:53

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;
  }
}

It remains to get rid of the cycle and two comparisons. I thought to replace the cycle with recursion. And I don't even know what to do with the comparison. The language does not allow casting to the boolean type, which makes me very sad.
What can you advise? Maybe there are easier ways?
PS The method should work simultaneously for integers and real numbers.
PPS
Suddenly, someone will come in handy, here is the solution:
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

2 answer(s)
V
VitGun, 2016-09-08
@VitGun

Ternary operator?

M
Maxim Moseychuk, 2016-09-08
@fshp

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 question

Ask a Question

731 491 924 answers to any question