Floating point representations seem to do integer arithmetic correctly - why?

前端 未结 8 1305
死守一世寂寞
死守一世寂寞 2021-01-06 10:41

I\'ve been playing around with floating point numbers a little bit, and based on what I\'ve learned about them in the past, the fact that 0.1 + 0.2 ends up bein

8条回答
  •  灰色年华
    2021-01-06 11:00

    All floating point numbers can't be represented. it's due to the way of coding them. The wiki page explain it better than me: http://en.wikipedia.org/wiki/IEEE_754-1985. So when you are trying to compare a floating point number, you should use a delta:

    myFloat - expectedFloat < delta
    

    You can use the smallest representable floating point number as delta.

提交回复
热议问题