V3024. An odd precise comparison. Consider using a comparison with defined precision: Math.Abs(A - B) < Epsilon or Math.Abs(A - B) > Epsilon.

The analyzer has detected a suspicious code fragment where floating-point numbers are compared using operator '==' or '!='. Such code may contain a bug.

Let's discuss an example of correct code first (which will, however, trigger the warning anyway):

double a = 0.5;
if (a == 0.5) //ok

This comparison is correct. Before executing it, the 'a' variable is explicitly initialized to value '0.5', and it is this value the comparison is done over. The expression will evaluate to 'true'.

So, strict comparisons are permitted in certain cases - but not all the time. Here's an example of incorrect code:

double b = Math.Sin(Math.PI / 6.0); 
if (b == 0.5) //err

The 'b == 0.5' condition proves false because the 'Math.Sin(Math.PI / 6.0)' expression evaluates to 0.49999999999999994. This number is very close but still not equal to '0.5'.

One way to fix this is to compare the difference of the two values against some reference value (i.e. amount of error, which in this case is expressed by variable 'epsilon'):

double b = Math.Sin(Math.PI / 6.0); 
if (Math.Abs(b - 0.5) < epsilon) //ok

You should estimate the error amount appropriately, depending on what values are being compared.

The analyzer points out those code fragments where floating-point numbers are compared using operator '!=' or '==', but it's the programmer alone who can figure out whether or not such comparison is incorrect.


This diagnostic is classified as:

You can look at examples of errors detected by the V3024 diagnostic.

Bugs Found

Checked Projects
Collected Errors
14 526
This website uses cookies and other technology to provide you a more personalized experience. By continuing the view of our web-pages you accept the terms of using these files. If you don't want your personal data to be processed, please, leave this site. Learn More →