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

后端 未结 3 1210
夕颜
夕颜 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.

    0 讨论(0)
  • 2020-12-19 19:42

    This is expected behavior for floating point values. They cannot be 100% accurately represented.

    You can use the XCTAssertEqualWithAccuracy function to assert floating point values are within a given range of each other.

    The reason println prints the same value for all is because it internally rounds them to two decimals (I assume).

    0 讨论(0)
  • 2020-12-19 19:42

    This is not a Swift specific issue, this is related to the fact how decimal numbers are created in computers and what is their precision. You will need to work with DBL_EPSILON.

    0 讨论(0)
提交回复
热议问题