laziness, impatience, and hubris | |
PerlMonks |
Integers sometimes turn into Reals after substractionby rduke15 (Beadle) |
on May 14, 2016 at 10:43 UTC ( [id://1163025]=perlquestion: print w/replies, xml ) | Need Help?? |
rduke15 has asked for the wisdom of the Perl Monks concerning the following question: Just bumped into this problem. Some calculations seem to make a number become a "hidden" real number instead of an integer. The number prints as an integer, but after a substraction with another integer, the result is a real. #!/usr/bin/perl use strict; use warnings; my ($x1, $x2) = (256080, 258160); my $diff = $x2 - $x1; print "x1=$x1, x2=$x2, diff=$diff\n"; # OK $x2 = 1000*240 + 1000*18 + 1000*( 4/25 ); $diff = $x2 - $x1; print "x1=$x1, x2=$x2, diff=$diff\n"; # Also OK $x2 = 1000 * ( 4*60 + 18 + 4/25 ); $diff = $x2 - $x1; print "x1=$x1, x2=$x2, diff=$diff\n"; # $x2 is integer, but $diff is real! The output is: x1=256080, x2=258160, diff=2080 x1=256080, x2=258160, diff=2080 x1=256080, x2=258160, diff=2080.00000000003 Or the short one-liner version: perl -e '$x1=256080; $x2 = 1000 * ( 4*60 + 18 + 4/25 ); $diff=$x2-$x1; print "x1=$x1, x2=$x2, diff=$diff, Perl=$^V\n";' I tried this on Perl versions v5.14.2, v5.18.2 and v5.20.2 with the same result. It is disconcerting that $x2 prints as "258160", but becomes something else when used in a substraction.
Back to
Seekers of Perl Wisdom
|
|