next up previous contents index
Next: String comparison Up: Comparisons Previous: Comparisons   Contents   Index


Numerical comparison

For a numerical comparison, available operators are A couple of cautionary notes must be raised about specifying conditions involving equality of numbers. The first is to note that equality of numbers is tested with the == operator, and not a single =. This can be confusing: consider the snippet:
my $i = 22;
my $j = 44;
if ($i = $j) {
  print qq{\$i and \$j are equal\n};
}
which will report that $i and $j are equal. The reason for this is that, as a statement, the assignment $i = $j, which assigns the value of $j to $i, is true, and thus the enclosing statements are evaluated. The second cautionary note involves comparing numerical values themselves. Consider
my $i = 4/3;
my $j = 4/3 + 3/2 - 1.5;
if ($i == $j) {
  print qq{\$i and \$j are equal\n};
}
This will not print out that $i and $j are equal, even though mathematically we can show they are. The reason for this is that computers only store integers exactly (up to a maximum size); floating point numbers are stored only up to a certain accuracy, which then leads to round-off errors. If you wanted to compare two floating point numbers, it is generally a good idea to specify a tolerance to which you would consider them equal:
my $i = 4/3;
my $j = 4/3 + 3/2 - 1.5;
my $diff = abs($i - $j);   # abs() takes the absolute value
my $epsilon = 0.0000001;   # can also write this as 1e-7 [ 10^(-7) ]
if ($diff < $epsilon) {
  print qq{\$i and \$j are close enough};
}

next up previous contents index
Next: String comparison Up: Comparisons Previous: Comparisons   Contents   Index