Subject: | Unexpected behaviour with floating point errors |
The output of the following test is surprising:
#!/home/ben/software/install/bin/perl
use warnings;
use strict;
use Test::More;
use Math::Factor::XS ':all';
my @p = (0.7, 0.1);
my @q;
for my $x (@p) {
for my $y (@p) {
push @q, $x * $y;
}
}
my @r = map {$_ * 100} @q;
print "\@r = @r\n";
for my $r (@r) {
my @factors = prime_factors ($r);
if ($r == 7) {
is (scalar @factors, 1);
is_deeply (\@factors, [7]);
}
else {
print $r - 7, "\n";
print "$r -> @factors\n";
}
}
done_testing ();
Output follows:
@r = 49 7 7 1
42
49 -> 2 2 2 2 3
-8.88178419700125e-16
7 -> 2 3
-8.88178419700125e-16
7 -> 2 3
-6
1 ->
1..0
# No tests run!
What Perl prints as "7" is taken to be 6 by the module and factorized as "2 3". The difference between the value 7 and the actual value is a tiny floating point error.
I would suggest that either the module should round the number to the nearest integer, or simply refuse to process a non-integer value.