NAME
Test::Approximate - test for approximate numeric equality
VERSION
version 0.101
SYNOPSIS
use Test::Approximate;
set_dop(3); # this is the default value
is_approx 3, 3.001, 'close enough';
set_dop(1);
is_approx 3.0, 3.4, 'also close enough';
set_dop(2);
isnt_approx 3.0, 3.4, 'different';
DESCRIPTION
Test::Approximate provides tests that can be used to compare floating-point numbers for approximate equality (is_approx()
) and inequality (isnt_approx()
). This is achieved using the concept of digits of precision, or DOP. The DOP of a number are a fixed number of significant digits of that number. For example, with 3 DOP 1,234,000 would be 1,230,000 and 0.000 1234 would be 0.000 123.
By default, 3 DOP are used.
METHOD
To compare the two numbers $actual
and $expected
, a (power-of-ten) scaling factor for $expected
is determined, such that, when multiplied by it, there will be DOP digits before the decimal point. The absolute value of the difference between $actual
and $expected
is multiplied by the scaling factor and rounded to the nearest integer. If this value is zero, the two values are deemed to be approximately the same (or non-zero in the case of isnt_approx()
).
DIAGNOSTICS
is_approx()
and isnt_approx()
will emit diagnostics whenever a test fails.
For example,
set_dop(2);
is_approx 1000,1100; # fails
produces the following output:
not ok 1
# Failed test at ... line 30.
# DOP: 2
# Delta: 100
# Multiplier: 0.01 (1e-2)
# Diff: round(1)
# Comparison: 1 == 0
DOP: the digits of precision used.
Delta: the absolute difference between $actual
and $expected
.
Multiplier: factor used to make all DOP occur before the decimal point.
Diff: delta after scaling.
Comparison: the comparison used for the test.
FUNCTIONS
is_approx
is_approx $actual, $expected, $name;
Compares $actual
to $expected
as described above and generates an appropriate standard pass/fail test result. As is usual with Perl testing modules, $name
is optional.
isnt_approx
isnt_approx $actual, $expected, $name;
The opposite of is_approx()
. The test will pass if $actual
and $expected
are sufficiently different.
set_dop($new_dop)
set_dop(4); # set precision to 4 DOP
print set_dop(); # 4
set_dop()
is used to set the precision of is_approx()
and isnt_approx()
. It takes a single, optional, argument that represents the DOP to use in the comparisons. $new_dop
must be an integer between 1 and 14 inclusive and will be shoehorned into that range if necessary. $new_dop
is returned as the value of the function.
If $new_dop
is absent, set_dop
just returns the current value of DOP.
See DESCRIPTION above for more about DOP.
AUTHOR & COPYRIGHT
Copyright 2020 by Brian Greenfield < briang @ cpan dot org >.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.