Home c How to compare real numbers in C for more or less?

How to compare real numbers in C for more or less?




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

Everywhere they write that you cannot use the usual comparison operators, but I have not found a clear explanation of how to do this correctly.

Answer 1, authority 100%

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

Or use more complex comparison methods –
eg mixing absolute and relative errors

if (Abs (x - y) & lt; = Max (absTol, relTol * Max (Abs (x), Abs (y))))

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

if (a & gt; b) ... else ...

decide which is more, which is less.

Answer 2, authority 36%

a & lt; b-EPS
a & lt; = b + EPS
fabs (a-b) & lt; = EPS

Answer 3, authority 7%

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

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions