Dealing with floating point errors in .NET

后端 未结 3 804
醉酒成梦
醉酒成梦 2020-12-18 00:07

I\'m working on a scientific computation & visualization project in C#/.NET, and we use doubles to represent all the physical quantities. Since floating-po

3条回答
  •  眼角桃花
    2020-12-18 00:51

    Your best answer is always better algorithms, of course. But it seems to me that if your values aren't all within a couple of orders of magnitude of 1, the using a fixed epsilon is not a good strategy. What you want to do instead is to insure that the values are equal to within some reasonable precision.

    // are values equal to within 12 (or so) digits of precision?
    //
    bool ApproxEquals(double d1, double d2) {
        return Math.Abs(d1 - d2) < (Math.Abs(d1) * 1e-12);
    }
    

    If this were C++, then you could also pull some tricks to compare the mantissa and exponent separately, but I can't think of any way to do this safely in unmanged code.

提交回复
热议问题