There are a couple of points to be wary of in any processing like this. One is that floating point numbers are not equivalent to rational numbers. Some results will look something like
$x = 75;
$y = sprintf("%1.15f", 75/5);
print $y;
# 14.999999
($i, $f) = split(/\./, $y);
print "Integer part: $i\nFractional part: $f\n";
# Integer part 14
# Fractional part 0.999999
Note: this is an example, not necessarily an actual result.
Which is, of course, right, and is also, probably, useless. (I'm currently ignoring the bignum pragma).
What I would tend to do would be something like this:
- Use sprintf with an appropriate format to round to a desired precision.
- Split on the radix point (in the US, this is the period, ".")
As an example:
#!perl
use strict;use warnings;
my $fmt = "%1.5f"; # set 5 decimal places
while(<DATA>){
chomp;
(my $dividend, my $divisor) = split(/\s+/,$_,2);
(my $int, my $frac) = split(/\./, (sprintf($fmt, ($dividend/$div
+isor))),2);
print "Integer part: $int\tFractional part: $frac\n";
}
__DATA__
1 2
2 1
3 4
4 3
127 5
75 5
Produces:
Integer part: 0 Fractional part: 50000
Integer part: 2 Fractional part: 00000
Integer part: 0 Fractional part: 75000
Integer part: 1 Fractional part: 33333
Integer part: 25 Fractional part: 40000
Integer part: 15 Fractional part: 00000
The other possible 'gotchas' include the possibility that results may not be consistent between platforms or between Perls built with different compilers on the same platform. Floating point arithmetic is fraught with peril.
emc
Experience is a hard teacher because she gives the test first, the lesson afterwards.
Vernon Sanders Law
|