in reply to Comparing masses in two txt files

You want to do something to every item in @List1 with every item in @List2, so you want nested loops.
my $count = 0; for my $list1 (@List1) { for my $list2 (@List2) { if (abs($list1 - $list2) <= .2) { $count++ } } } print("$count\n");

But beware that checking floating point numbers for equality is basically impossibe — Does anyone have a good link they can provide here? — so you might not get the results you want. .2, for example, is a periodic number in binary (just like 1/3 is a periodic number in decimal). You might need to introduce a tolerance.

my $tol = 2**(-30); # ~ 0.000000001 my $count = 0; for my $list1 (@List1) { for my $list2 (@List2) { if (abs($list1 - $list2) - $tol <= .2) { $count++ } } } print("$count\n");

Replies are listed 'Best First'.
Re^2: Comparing masses in two txt files
by CountZero (Bishop) on Nov 05, 2008 at 19:30 UTC
    But beware that checking floating point numbers for equality is basically impossibe
    But even if some real numbers cannot be exactly represented in binary, at least they are both exactly misrepresented in the same way, so checking for equality should still work.

    I thought that this was only a problem if you were calculating with them:

    print .2 == .2 ? 'equal' : 'not equal'; equal print .2 *10 == 2 ? 'equal' : 'not equal'; equal print .1999999999999999 *10 == 2 ? 'equal' : 'not equal'; not equal print .19999999999999999 *10 == 2 ? 'equal' : 'not equal'; equal print .20000000000000001 *10 == 2 ? 'equal' : 'not equal'; equal print .2000000000000001 *10 == 2 ? 'equal' : 'not equal'; not equal
    So on the Perl on my machine (AS Perl 5.8.8) .2 seems to be anything between .19999999999999999 and .20000000000000001.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re^2: Comparing masses in two txt files
by lostjimmy (Chaplain) on Nov 05, 2008 at 19:30 UTC