Why do I see a double variable initialized to some value like 21.4 as 21.399999618530273?

前端 未结 14 2009
名媛妹妹
名媛妹妹 2020-11-21 23:41
double r = 11.631;
double theta = 21.4;

In the debugger, these are shown as 11.631000000000000

14条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-21 23:50

    I've come across this before (on my blog) - I think the surprise tends to be that the 'irrational' numbers are different.

    By 'irrational' here I'm just referring to the fact that they can't be accurately represented in this format. Real irrational numbers (like π - pi) can't be accurately represented at all.

    Most people are familiar with 1/3 not working in decimal: 0.3333333333333...

    The odd thing is that 1.1 doesn't work in floats. People expect decimal values to work in floating point numbers because of how they think of them:

    1.1 is 11 x 10^-1

    When actually they're in base-2

    1.1 is 154811237190861 x 2^-47

    You can't avoid it, you just have to get used to the fact that some floats are 'irrational', in the same way that 1/3 is.

提交回复
热议问题