Strange problem comparing floats in objective-C

后端 未结 7 2367
别跟我提以往
别跟我提以往 2020-11-27 16:25

At some point in an algorithm I need to compare the float value of a property of a class to a float. So I do this:

if (self.scroller.currentValue <= 0.1)          


        
7条回答
  •  迷失自我
    2020-11-27 17:17

    In C, a floating-point literal like 0.1 is a double, not a float. Since the types of the data items being compared are different, the comparison is done in the more precise type (double). In all implementations I know about, float has a shorter representation than double (usually expressed as something like 6 vs. 14 decimal places). Moreover, the arithmetic is in binary, and 1/10 does not have an exact representation in binary.

    Therefore, you're taking a float 0.1, which loses accuracy, extending it to double, and expecting it to compare equal to a double 0.1, which loses less accuracy.

    Suppose we were doing this in decimal, with float being three digits and double being six, and we were comparing to 1/3.

    We have the stored float value being 0.333. We're comparing it to a double with value 0.333333. We convert the float 0.333 to double 0.333000, and find it different.

提交回复
热议问题