Dealing with floating point errors in .NET

后端 未结 3 1592
囚心锁ツ
囚心锁ツ 2020-12-18 00:03

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:36

    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).

提交回复
热议问题