I am having some trouble with calculations in Perl (v5.10.1) due to floating point numbers:
#!/usr/bin/perl
use strict;
use warnings;
use POSIX;
my $x1 = 1500;
my $x0 = 1000;
my $dx = 100/3;
print "($x1-$x0)/$dx \n"; #(1500-1000)/33.3333333333333
print my $a=(($x1-$x0)/$dx), "\n"; #15
print my $b=floor(($x1-$x0)/$dx), "\n"; #14
print my $c=floor($a), "\n"; #14
print floor(15), "\n"; #15
print my $d=floor(sprintf("%.0f", ($x1-$x0)/$dx)), "\n"; #15
Why is the output 14 sometimes? Isn't the value 15 saved as it shows in $a
and therefore used floor
on the value 15? The comparison of $a
and $c
leaves me really puzzled...
I read this but can't figure it out. I also found the workaround with sprintf
which isn't very handy in my opinion.