An example of seemingly equal float variables not equal

Can someone show me an example of two C # variables containing float values ​​that “seem” to be equal, but this is actually not the case. When I say “seem equal”, I mean that they intuitively seem to be equal.

The reason I'm looking for such an example is because I have code that compares two float variables for equality, and Visual Studio warns me that Comparison of floating point numbers can be unequal due to the differing precision of the two values.. I understand that the float variables are not exact (here is the https://stackoverflow.com/a/3/4546/... where it is discussed and explained very clearly), but I cannot find an actual example where there are two values ​​that seem to be equal are actually considered different using C #.

For example, the first answer to the SO question that I referred to earlier mentions that 9.2they are 92/10internally represented differently, so I wrote the following code to check whether C # will treat them as equal or not, and the result is that they are considered equal .

var f1 = 92f / 10f;
var f2 = 9.2f;
if (f1 == f2)
{
    Console.Write("Equal, as expected");
}
else
{
    Console.Write("Surprisingly not equal");
}

So, I am looking for an example f1and f2that "seem" equal, but make C # treat them as different.

+4
source share
2 answers

If you don't insist on type float( Single), but really want to use any type of floating point ( Single, Double), you can try:

   if (Math.Sqrt(2.0) * Math.Sqrt(2.0) == 2.0) 
     Console.Write("Equal, as expected");
   else 
     Console.Write("Surprisingly not equal");
+3
source

. value1 value2 toSum * 10, . , . Float .

const float toSum = 1000000000.1f;
const int count = 10;
float value1 = 0;

for (int i = 0; i < count; i++)
{
    value1 += toSum;
}

float value2 = toSum * count;

var equal = value1 == value2;
+3

Source: https://habr.com/ru/post/1678048/


All Articles