Simple Floating Point Equality Check in C++

December 21st, 2015 - Software(1 min)

TL;DR: Here you can see a handmade comparison function for floating point values.

While working on a C++ project using templates, I had to perform an equality to see if two values are identical. While the == is OK for integer values, it is not really OK for floating point values. At that point, you have several options:

• Write inline code depending on instantiation (type conditions)
• Write a macro (I’m not fond of macros really)
• Write a (global) function

I’m sure there are others…

Solution

I’ve chose to write a comparison function myself, just to do a bit of exercise. The header is:

``````//
// Created by Laur Ivan on 15/12/15.
//

#ifndef CHECKS_H
#define CHECKS_H

#define DEFAULT_TOLERANCE 0.00001 // a small enough tolerance

bool check(double v1, double v2, double tolerance);

bool check(double v1, double v2);

#endif //CHECKS_H``````

and the source:

``````//
// Created by Laur Ivan on 15/12/15.
//

#include <math.h>
#include "checks.h"

/**
* Check if the two values are cloe enough
*/
bool check(double v1, double v2, double tolerance) {
double delta = fabs(v1 - v2);
return delta < tolerance;
}

bool check(double v1, double v2) {
return check(v1, v2, DEFAULT_TOLERANCE);
}``````

This is not rocket science, just a simple comparison function, with a shortcut for the default tolerance. These days you can add variable arguments to C++ functions, but I’ve elected not to do that :)

HTH,

Tagged with
All Tags
Share on

A little experiment: