-2

Code:

const float A = 0.1f;
float a = A;
Console.WriteLine(a == A);
Console.WriteLine(a * 10 == A * 10);

Output:

True
False

Code:

const double A = 0.1d;
double a = A;
Console.WriteLine(a == A);
Console.WriteLine(a * 10 == A * 10);

Output is

True
True

My environment is .NET Framework 4.8 32bit Console Application. I wonder why a * 10 == A * 10 is false when a variable type is float. I do not think this is related floating-point arithmetic accuracy problem because I assigned the same value(0.1f). Could you explain?

Falto
  • 7
  • 1
  • 2
  • can’t replicate on .net 7.0 https://dotnetfiddle.net/2P8CsC | but its as OP is saying on .net framework https://dotnetfiddle.net/7XOKbp – Rand Random Aug 27 '23 at 18:55
  • This seems to be specific to the x86 platform, it doesn't happen with .NET 4.8 on x64 either. There is no specific clue about what happened [in the assembly](https://sharplab.io/#v2:EYLgdgpgLgZgHgGiiAhgZwLYB8ACAmARgFgAoHAZgAJ9KBhSgb1MpeqpwBZKBZACgEpGzViICQogMYB7MGiiUYAGykp5AQUoBeSgAYAdARgBuUkpXyUWympNkCATl6XN2tf1s4HTygCpKBHS1XX38dd2EWAF9SSKA===) but floating point semantics on x86 are particularly cursed in general. – harold Aug 27 '23 at 19:00
  • 2
    Does this answer your question? ['const float' value different than 'float' when casting to 'int' in C#](https://stackoverflow.com/q/24016294/11683) – GSerg Aug 27 '23 at 19:00
  • Does this answer your question? [(.1f+.2f==.3f) != (.1f+.2f).Equals(.3f) Why?](https://stackoverflow.com/q/15117037/11683) – GSerg Aug 27 '23 at 19:03
  • Does this answer your question? [Is floating-point math consistent in C#? Can it be?](https://stackoverflow.com/q/6683059/11683) – GSerg Aug 27 '23 at 19:05
  • It's best to always assume that floats or doubles are inexact (except for 0.0 or 0.0f). If you assume inexactitude, and code for inexactitude, you'll always be safe (but, don't assume some calculation that _should be_ 0.0 or 0.0f is 0.0 or 0.0f) – Flydog57 Aug 27 '23 at 20:33
  • You should treat floating point numbers (both `float` and `double`) as if they were real-world measured values. So, as an example, should you take two sticks of butter from the supermarket and weigh them you might get 510g and 510g - but you know that as real-world items they are not the same weight. So the best you can do is say that ±2g they are the same. You should do the same in code. `if (Math.Abs(a * 10 - A * 10) < 0.0002))`. – Enigmativity Aug 28 '23 at 06:03
  • thankforcomment – Falto Sep 01 '23 at 17:10

0 Answers0