Binary floating point cannot represent 0.01 from base 10 exactly, close but not exact. Here is an example of rounding the printout using printf():
Update: I got a suggestion to make my warning about the use of $a and $b more prominent. $a and $b are Perl reserved variables and are used by sort amoungst other functions. Users should not use these variables. Use $x or $y or something else instead. Following my own advice, I changed from $a to $x below. Here the OP's use of $a "worked", but it is a bad habit to get into.
#!usr/bin/perl
use strict;
use warnings;
print "====float =======\n";
my $x=-50.123456;
for my $i (0...19)
{
printf "%i\t%.3f\n", $i,$x;
$x+=0.01;
}
$x=-71.123456;
for my $i (0...19)
{
printf "%i\t%.3f\n", $i,$x;
$x+=0.01;
}
__END__
====float =======
0 -50.123
1 -50.113
2 -50.103
3 -50.093
4 -50.083
5 -50.073
6 -50.063
7 -50.053
8 -50.043
9 -50.033
10 -50.023
11 -50.013
12 -50.003
13 -49.993
14 -49.983
15 -49.973
16 -49.963
17 -49.953
18 -49.943
19 -49.933
0 -71.123
1 -71.113
2 -71.103
3 -71.093
4 -71.083
5 -71.073
6 -71.063
7 -71.053
8 -71.043
9 -71.033
10 -71.023
11 -71.013
12 -71.003
13 -70.993
14 -70.983
15 -70.973
16 -70.963
17 -70.953
18 -70.943
19 -70.933
Update: added similar comment above and changed $a to $x.
Here it is ok, but $a and $b are reserved Perl variables and shouldn't be used by users. Use $x or $y instead. |