How in C to find out which of the real numbers is greater?

Everywhere they write that it is impossible to use the usual comparison operators, but I did not find a clear explanation of how to do it correctly.

3 answers 3

Difficulties of comparison arise when you need to check two numbers for equality - in this case, you should build on a specific task - the mathematical formulation of the problem should suggest whether it is enough to compare the difference modulus with a pre-selected value that is responsible for the comparison accuracy (absolute error). It is suitable, for example, if the task is well translated into a dimensionless form, and all numbers in it take values ​​between -1 and 1.

Or use more sophisticated comparison methods - for example , mixing absolute and relative errors

 if (Abs(x - y) <= Max(absTol, relTol * Max(Abs(x), Abs(y)))) 

That is, you can, one of the ways to first make sure that the numbers are significantly different, and then the usual:

if(a>b) ... else ...

decide which is more, which is less.

     a < b-EPS a <= b+EPS fabs(ab) <= EPS 
    • four
      Without explanation, what is shown here is nothing is clear (especially to those who ask about the comparison of numbers). - Kromster
    • one
      Who is in the subject, guess, but for the rest is really worth explaining. - dsnk

    How does float appear in memory? According to the IEEE 754 format. In this format, the number is represented by three fields. sign -1 bit, order - 8 bits, mantissa (23 bits) Accordingly, the mantissa itself is all important. It will then be converted to binary format and a comparison will be made on it, everything that is not a multiple of 2 will have an error, respectively, it is necessary to compare up to a certain decimal place. Guys, I do not work with C and C ++ and C #, but it’s logical that you calculate the module of their differences and compare them with the required accuracy. If the modulus of the difference is less than accuracy - the numbers are equal. If you need to compare more less then after the difference module, check again if they are not equal.

    • one
      Excellent introduction, but the answer to the top - starter question "how to compare" is not ... - Kromster