Dealing with floating point errors in .NET

后端 未结 3 796
醉酒成梦
醉酒成梦 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 01:01

    Due to the way real numbers are typically represented, You can do this in C (and probably in unsafe C#):

    if (llabs(*(long long)&x - *(long long)&y) <= EPSILON) {
        // Close enough
    }
    

    This is obviously non-portable and probably a bad idea, but it has the significant advantage of scale-independence. That is, EPSILON can be some small constant like 1, 10 or 100 (depending on your desired tolerance), and it will handle proportional rounding errors correctly regardless of the exponent.

    Disclaimer: This is my own private invention, and has not been vetted by anyone with a clue (like, say, a mathematician with a background in discrete arithmetic).

提交回复
热议问题