How to compare CGFloat in XCTestCase?

I donโ€™t understand this at all. What is the problem?

I tried to introduce 1.0 , 1.0f , (CGFloat) 1.0 and (CGFloat)(2.0 - 1.0) . Each time with the same error.

Screenshot from xcode

+6
source share
3 answers

I would recommend using FLT_EPSILON for this:

XCTAssertEqualWithAccuracy(mov.lastDelta, 0.0f, FLT_EPSILON, @"");

If you have no reason to demand more epsilon.

+17
source

The fractional part of your numbers, 0.9, cannot be accurately represented by a floating point. Some rounding will occur, and probably the reason for the failure.

0.9 = (1/2) + (1/4) + (1/8) + (1/64) + (1/128) + (1/1024) + (1/2048) + (1/16384 ) + (1/32768) + (1/262144), etc. Etc. = 0.8999978005, etc.

Fractions that look around the human eye may not be round in the binary system.

0.5 is a round number for cpu = (1/2).

0.75 is round for cpu = (1/2) + (1/4).

Even 0.9072265625 is round ((1/2) + (1/4) + (1/8) + (1/32) + (1/1024))

But not 0.9 or 0.1. Not even 0.2 :)

EDIT: And of course, use epsilon to compare floats.

+5
source

I changed to

 mov.value = 8.9 XCTAssertEqualWithAccuracy(mov.lastDelta, 0.0f, 0.001, @""); 

and it seems to work fine now ...

0
source

Source: https://habr.com/ru/post/955433/


All Articles