0

I am working on a simple app where I need to use Shunting-yard algorithm. To make sure that everything works fine I want to create unit tests obviously. One case is driving me crazy. I mean when subtraction and checking if result of 15.5 - 15.1 from my algorithm is the same as 0.4. Test fails with an error: XCTAssertEqual failed: ("Optional(0.40000000000000036)") is not equal to ("Optional(0.4)").

Any ideas how to avoid this loss of bits?

Both algorithm and expression in test case are based on doubles.

kkiermasz
  • 464
  • 2
  • 15
  • I suspect this is just https://stackoverflow.com/questions/588004/is-floating-point-math-broken. Do you have a different question than that? – Rob Napier Jul 01 '19 at 21:22
  • You may want to test whether your algorithm matches IEEE math, in which case you should test against the Swift expression `15.5-15.1`. That's 0.40000000000000036, so your algorithm looks correct. You can try yourself: `echo "print(15.5-15.1)" | swift -` – Rob Napier Jul 01 '19 at 21:26

0 Answers0