1. Perl
  2. Numerical value
  3. Floating point comparison

Compare floating point

Since computers use binary numbers internally, errors occur in the calculation process for decimal numbers that cannot be expressed in binary numbers. In order to ignore the effect of errors that occur in the process of binary arithmetic, it is necessary to round the numbers to a certain significant digit and compare them.

Use sprintf function to round the digits.

sprintf("%.5g", $num1);

"%.5g" is a format specification that rounds a floating point number to 5 significant digits.

Example program

This is an example to compare floating point numbers.

use strict;
use warnings;

my $num1 = 1;
my $num2;

# Add 0.1 10 times
for my $i (1 .. 10) {
  $num2 += 0.1;

print "(1) There is an error.\n";
if ($num1 != $num2) {
  print'$num1 and $num2 are not equal'. "\n\n";

print "(2) -1 Floating point rounded to 5 decimal places and compared (equal).\n";
my $num1_cut5 = sprintf("%.5g", $num1);
my $num2_cut5 = sprintf("%.5g", $num2);

print $num1_cut5 . "\n";
print $num2_cut5 . "\n";

Related Informatrion