### TranThuyLuc's blog

By TranThuyLuc, 5 years ago,

In many contest problems in Codeforces where the results require float point number, there is often something like this:

However, the normal way to check whether two float point numbers are equal is something like this:

const double EPS = 1e-9;

bool isEqual(double x, double y){
return abs(x - y) < EPS;
}


Is the way Codeforces use more precise? Should I use this way for comparing float point numbers instead of the normal way?

• +8

 » 5 years ago, # | ← Rev. 2 →   +5 I think they use both ways and your answer is considered correct if it's equal to the jury's answer by at least one of the two ways. More information here.
•  » » 5 years ago, # ^ | ← Rev. 2 →   0 I think so.Anyway, the first way tends to work better for me, especially when I need to compare an integer with a double.Is there any reason to use the second way instead of the first way?
•  » » » 5 years ago, # ^ |   0 How do you define better in this case?
•  » » » » 5 years ago, # ^ |   0 As stated in the formula, the first way also considers with the magnitude of 2 numbers.Therefore in case of comparing very large numbers and the precision preserved is very small, the first way will output more precise result.Moreover, when I extend this formula to support smaller and larger operators, the first way seem to be the only way.
 » 5 years ago, # | ← Rev. 2 →   +27 If the checker uses testlib, then the source code used is available at GitHub.
 » 5 years ago, # | ← Rev. 2 →   +22 A large fraction of contest problems uses Testlib for checkers. The standard Testlib checkers include both absolute-or-relative error and absolute error checkers. Note that the absolute-or-relative check accepts strictly more answers than just the absolute check. For numbers less than one in magnitude (probabilities are an example), they are essentially the same. For large numbers, however, the absolute-or-relative check accepts more answers. As an example, consider EPS=1E-9 and answers of order 1E+6. If the jury answer is 1 000 000, the relative error check accepts numbers 999 999.999 through 1 000 000.001. As most solutions to contest problems use floating point for real numbers, the relative error check makes a lot of sense here. The Testlib accounts for double precision at the point of comparison as well, see what TianyiChen linked.