Rule of thumb to test the equality of two doubles in C#?

后端 未结 6 1906
忘掉有多难
忘掉有多难 2020-12-06 17:00

Let\'s say I have some code that does some floating point arithmetic and stores the values in doubles. Because some values can\'t be represented perfectly in binary, how do

6条回答
  •  -上瘾入骨i
    2020-12-06 17:02

    It depends a bit on what kind of values you're working with. If you're working with numbers where you only care about 2 decimal points it might be ok to just use 0.001. You might be able to use Epsilon sometimes, but normally I think not.

    Edit: Removed reference to currency since it distracted from the point.

    Quote from MSDN:

    If you create a custom algorithm that determines whether two floating-point numbers can be considered equal, you must use a value that is greater than the Epsilon constant to establish the acceptable absolute margin of difference for the two values to be considered equal. (Typically, that margin of difference is many times greater than Epsilon.)

提交回复
热议问题