Perl: how to compare floating numbers

I wrote the following Perl script. However, it does not print "1". I did some research, and it seems to be due to the IEEE representation of a floating point number. So, is there a better way to compare floating point numbers in Perl?

for (my $tmp = 0.1; $tmp <= 1; $tmp+=0.05){print $tmp."\n"}

Exit:

0.1
0.15
0.2
0.25
0.3
0.35
0.4
0.45
0.5
0.55
0.6
0.65
0.7
0.75
0.8
0.85
0.9
0.95
+4
source share
4 answers

All calculations that use floating point numbers may have precision errors, and if you reuse the results, then these exact erros add up. One thing to learn from this is to never use float as a loop control variable.

Use something like

for (my $tmp=2; $tmp<=20; tmp++) {
    print $tmp/20.0, "\n";
}

. ($a, $b)

if (abs($a - $b) < 0.000001)

- , - , , , .

+8

, - 100.

, , ;

for (my $tmp = 10; $tmp <= 100; $tmp+=5){print $tmp/100 ."\n"}

:

0.1
0.15
0.2
0.25
0.3
0.35
0.4
0.45
0.5
0.55
0.6
0.65
0.7
0.75
0.8
0.85
0.9
0.95
1
+4

This is a classic programming situation and is well explained here.

The fix is ​​to use integer arithmetic instead and write it like this:

for (my $tmp = 10; $tmp <= 100; $tmp += 5) {
  print $tmp/100, "\n"
}

Exit

0.1
0.15
0.2
0.25
0.3
0.35
0.4
0.45
0.5
0.55
0.6
0.65
0.7
0.75
0.8
0.85
0.9
0.95
1
0
source
sign=$(perl -E "printf '%.4f', 434.5678 - 2734.4395"); if [ "${sign:0:1}" = "-" ]; then echo -e "434.5678 < 2734.4395\n"; fi

Result:

434.5678 < 2734.4395
0
source

Source: https://habr.com/ru/post/1525495/


All Articles