Swift: Double conversion inconsistency. How to correctly compare Doubles?

后端 未结 3 1302
夕颜
夕颜 2020-12-19 18:40

I have a very simple function to convert temperature from ˚C TO ˚K.

func convertKelvinToCelsius(temp:Double) ->Double {
        return temp - 273.15
}
         


        
3条回答
  •  庸人自扰
    2020-12-19 19:28

    Swift, like most languages, uses binary floating point numbers.

    With binary floating point numbers, some numbers can be represented exactly, but most can't. What can be represented exactly are integers unless they are very large (for example, 100000000000000.0 is fine), and such integers multiplied or divided by powers of two (7.375 is fine, it is 59.0 / 8, but 7.3 isn't).

    Every floating point operation gives you the exact result, rounded to the nearest floating-point number. So you get

    200.0 -> Exactly 200
    273.15 -> A number very close to 273.15
    200 - 273.15 -> A number very close to -73.15
    -73.15 -> A number very close to -73.15
    

    If you compare two numbers that are both very very close to -73.15 they are not necessarily equal. That's not a problem of the == operator; that one will determine correctly whether they are equal or not. The problem is that the two numbers can actually be different.

提交回复
热议问题