Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing for Floating-Point Equivalence in Perl

I'm writing unit tests in Perl using Test::More. I'm used to some of the constructs from cxxunit, and in particular I'm missing TS_ASSERT_DELTA. For those who've not seen TS_ASSERT_DELTA, it looks like this:

TS_ASSERT_DELTA( 1.0, 1.1, 0.5 );   // this test will pass
TS_ASSERT_DELTA( 1.0, 1.1, 1e-10 ); // this test will fail

Is there a Perl equivalent for floating-point comparison? Or does everyone just write an obvious function for this? I'm currently working with this:

sub compare_float_delta {
    my $n1    = shift;
    my $n2    = shift;
    my $delta = shift;
    return( abs($n1-$n2) < $delta );
}

To me this seems like something the test framework should provide. Is that idea right, or should I just call float_compare_delta and move on with my life?

like image 664
James Thompson Avatar asked Dec 13 '22 01:12

James Thompson


1 Answers

You can use a specific module from CPAN: Test::Number::Delta

like image 124
Miguel Prz Avatar answered Jan 06 '23 21:01

Miguel Prz