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.
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.
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 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.
Source: https://ru.stackoverflow.com/questions/461464/
All Articles
>,<. They can be used with real numbers in C. - Petr Abdulin