1

While reading about floating point number precision I made a small test and expected the result1 to be true but it turned out to be the opposite. I somehow couldn't find a reasonable explanation, help please :)

Input

using System;
                    
public class Program
{
    public static void Main()
    {
        float a = 0.1f;
        float b = 0.2f;
        float c = 0.1f + 0.2f;
        float d = a + b;
        bool result1 = (a + b) == (0.1f + 0.2f);
        bool result2 = c == d;
        Console.WriteLine("result1 == " + result1);
        Console.WriteLine("result2 == " + result2);
    }
}

Output:

result1 == False
result2 == True
tc07
  • 235
  • 1
  • 3
  • 9
  • https://stackoverflow.com/a/4152893/3792469 - Does this answer help you answer the question? – Viv Jun 04 '21 at 17:55
  • `0.1` as well as `0.2` and `0.3` when represented as *binary* are *periodic fractions*, that's why you have *rounding* errors – Dmitry Bychenko Jun 04 '21 at 17:59
  • @DmitryBychenko I understand that adding 0.1f to 0.2f doesn't necessarily result in 0.3f but shouldn't a + b return the same result as 0.1f + 0.2f (doesn't matter what the real result is) ? just like when comparing c and d – tc07 Jun 04 '21 at 18:04
  • @Viv I stil dont find it answering directly to my question, I dont understand why result1 and result2 are different or in other words, why assiging 0.1f+ 0.2f to c would make a difference here – tc07 Jun 04 '21 at 18:07
  • 1
    [JIT Optimization float problems](https://stackoverflow.com/questions/64472508/) is a better dupe; I suspect the reason is that `0.1f + 0.2f` is done by the compiler and `(a + b)` is done by the JIT and each is allowed to perform different optimizations. TLDR; **stop comparing floating-point values for equality**. – Dour High Arch Jun 04 '21 at 18:26
  • 1
    I still think they should go back to teaching slide rules in high school. After using a slide rule to do serious calculations, you have no problem understanding how just about every floating point number is an approximation (can anyone tell that I'm old) – Flydog57 Jun 04 '21 at 18:54
  • just for clarification - "I don't understand why result1 and result2 are different or in other words, why assiging 0.1f+ 0.2f to c would make a difference here". – tc07 Jun 04 '21 at 21:36

0 Answers0