Saturday, December 1, 2018

Swift's Unit Test: Comparing two floating-point numbers (in scientific notation)

Comparing two floating-point numbers in Unit test (using Swift 3's XCTAssertEqual() method) might fail if their precisions are different. For example, if the expected result is 3.3 but the actual result (of 10/3) is 3.333333333333333, the test fails. The solution is we specify the accuracy argument of the XCTAssertEqual() method to tell the framework that a small difference between their precisions do not matter.

let result = 3.3
XCTAssertEqual(result, 10/3, accuracy: 0.04)

In the code snippet above, the framework considers those two numbers are equal because they are just 0.033333333333333 different, which is less than the accuracy parameter 0.04.

Scientific Notation


In Swift, the double literal can be expressed in scientific notation like 1.234e10, which equals 12_340_000_000. The test in the example below will fail.

XCTAssertEqual(1.1234e10, 1.123e10)

To make the test successful, the accuracy parameter should be specified as following.

XCTAssertEqual(1.1234e10, 1.123e10, accuracy: 0.0004e10)
// 1.1234e10 = 11234_000_000
// 1.123e10  = 11230_000_000
// 0.0004e10 =     4_000_000

The accuracy value less than that such as 0.0003e10 or 0.0001e10 still make the test fail.




No comments:

Post a Comment