Is it possible to get 0 by subtracting two unequal floating point numbers?

后端 未结 12 1806
余生分开走
余生分开走 2021-01-30 07:50

Is it possible to get division by 0 (or infinity) in the following example?

public double calculation(double a, double          


        
12条回答
  •  梦毁少年i
    2021-01-30 08:36

    The core problem is that computer representation of a double (aka float, or real number in mathematical language) is wrong when you have "too much" decimal, for instance when you deal with double that can't be written as a numerical value (pi or the result of 1/3).

    So a==b can't be done with any double value of a and b, how to you deal with a==b when a=0.333 and b=1/3 ? Depending of your OS vs FPU vs number vs language versus count of 3 after 0, you will have true or false.

    Anyway if you do "double value calculation" on a computer, you have to deal with accuracy, so instead of doing a==b, you have to do absolute_value(a-b), and epsilon is relative to what you are modeling at that time in your algorithm. You can't have an epsilon value for all of your double comparison.

    In brief, when you type a==b, you have a mathemical expression that can't be translated on a computer (for any floating point number).

    PS: hum, everything I answer here is yet more or less in others responses and comments.

提交回复
热议问题