Skip to content

Commit

Permalink
Determine equality of floating point values as abs(A-B) < epsilon ins…
Browse files Browse the repository at this point in the history
…tead of A == B.

Precise equality can lead to wrong results due to small differences in values cause by rounding. Closes issue #561.
  • Loading branch information
plusvic committed Aug 2, 2018
1 parent f9a52f0 commit 803d42a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
5 changes: 3 additions & 2 deletions libyara/exec.c
Expand Up @@ -32,6 +32,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <string.h>
#include <assert.h>
#include <math.h>
#include <float.h>

#include <yara/globals.h>
#include <yara/arena.h>
Expand Down Expand Up @@ -1157,7 +1158,7 @@ int yr_execute_code(
pop(r1);
ensure_defined(r2);
ensure_defined(r1);
r1.i = r1.d == r2.d;
r1.i = fabs(r1.d - r2.d) < DBL_EPSILON;
push(r1);
break;

Expand All @@ -1166,7 +1167,7 @@ int yr_execute_code(
pop(r1);
ensure_defined(r2);
ensure_defined(r1);
r1.i = r1.d != r2.d;
r1.i = fabs(r1.d - r2.d) >= DBL_EPSILON;
push(r1);
break;

Expand Down
21 changes: 21 additions & 0 deletions tests/test-rules.c
Expand Up @@ -88,6 +88,27 @@ static void test_comparison_operators()
assert_true_rule(
"rule test { condition: 1.5 >= 1.0}", NULL);

assert_true_rule(
"rule test { condition: 1.0 != 1.000000000000001 }", NULL);

assert_true_rule(
"rule test { condition: 1.0 < 1.000000000000001 }", NULL);

assert_false_rule(
"rule test { condition: 1.0 >= 1.000000000000001 }", NULL);

assert_true_rule(
"rule test { condition: 1.000000000000001 > 1 }", NULL);

assert_false_rule(
"rule test { condition: 1.000000000000001 <= 1 }", NULL);

assert_true_rule(
"rule test { condition: 1.0 == 1.0000000000000001 }", NULL);

assert_true_rule(
"rule test { condition: 1.0 >= 1.0000000000000001 }", NULL);

assert_true_rule(
"rule test { condition: 1.5 >= 1}", NULL);

Expand Down

0 comments on commit 803d42a

Please sign in to comment.