Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.Sign up
GitHub is where the world builds software
Millions of developers and companies build, ship, and maintain their software on GitHub — the largest and most advanced development platform in the world.
Add a convenience function for floating-point comparisons #1441
This pull request adds a convenience class to assert that two floating-point numbers (or two sets of numbers) are equal to each other within some margin. You give the class the number you're expecting to get, and the class overrides the "==" operator to do the comparison behind the scenes with a reasonable margin for error. Most unit testing frameworks have some sort of
Tests and documentation are included. I ran all the tests on python2.7 and python3.4, but I'm a little worried that the way I use unicode in
Due to the intricacies of floating-point arithmetic, numbers that we would intuitively expect to be the same are not always so:
This problem is commonly encountered when writing tests, e.g. when making sure that floating-point values are what you expect them to be. One way to deal with this problem is to assert that two floating-point numbers are equal to within some appropriate margin:
However, comparisons like this are tedious to write and difficult to understand. Furthermore, absolute comparisons like the one above are usually discouraged in favor of relative comparisons, which can't even be easily written on one line. The
This was a challenge because it had to work in python2 and python3, which have almost opposite unicode models, and I couldn't use the six library. I'm also not sure the solution I found would work in python3 before python3.3, because I use the u'' string prefix which I think was initially not part of python3.
Some random thoughts:
@The-Compiler Thanks for pointing out
This commit also: - Dramatically increases the number of unit tests , mostly by borrowing from the standard library's unit tests for math.isclose(). - Refactors approx() into two classes, one of which handles comparing individual numbers (ApproxNonIterable) and another which uses the first to compare individual numbers or sequences of numbers.