From acf638f2bc87d0d5137af27f2750125117703774 Mon Sep 17 00:00:00 2001 From: Phil Nash Date: Wed, 17 Dec 2014 18:45:50 +0000 Subject: [PATCH] Added docs for floating point comparisons --- docs/assertions.md | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/docs/assertions.md b/docs/assertions.md index 5e839989..82bb96a3 100644 --- a/docs/assertions.md +++ b/docs/assertions.md @@ -17,12 +17,12 @@ The ```CHECK``` family are equivalent but execution continues in the same test c Evaluates the expression and records the result. If an exception is thrown it is caught, reported, and counted as a failure. These are the macros you will use most of the time Examples: - -```c++ +``` CHECK( str == "string value" ); CHECK( thisReturnsTrue() ); REQUIRE( i == 42 ); ``` + * **REQUIRE_FALSE(** _expression_ **)** and * **CHECK_FALSE(** _expression_ **)** @@ -30,10 +30,28 @@ Evaluates the expression and records the _logical NOT_ of the result. If an exce (these forms exist as a workaround for the fact that ! prefixed expressions cannot be decomposed). Example: -```c++ +``` REQUIRE_FALSE( thisReturnsFalse() ); ``` +### Floating point comparisons + +When comparing floating point numbers - especially if at least one of them has been computed - great care must be taken to allow for rounding errors and inexact representations. + +Catch provides a way to perform tolerant comparisons of floating point values through use of a wrapper class called ```Approx```. ```Approx``` can be used on either side of a comparison expression. It overloads the comparisons operators to take a tolerance into account. Here's a simple example: + +``` +REQUIRE( performComputation() == Approx( 2.1 ) ); +``` + +By default a small epsilon value is used that covers many simple cases of rounding errors. When this is insufficent the epsilon value (the amount within which a difference either way is ignored) can be specified by calling the ```epsilon()``` method on the ```Approx``` instance. e.g.: + +``` +REQUIRE( 22/7 == Approx( 3.141 ).epsilon( 0.01 ) ); +``` + +When dealing with very large or very small numbers it can be useful to specify a scale, which can be achieved by calling the ```scale()``` method on the ```Approx``` instance. + ## Exceptions * **REQUIRE_THROWS(** _expression_ **)** and