Rationalise (Canonise) the Fractions before Addition
Normally before fractions are added, they are rationalised;
i.e., they are put in a form where their denominators become
the same. This same denominator is the LCM of the
denominators of all the separate fractions.
After this is done, the new numerators can then be added together.
Steps for Addition of Fractions Perl code
The following steps will guide us in writing our code.
Let's illustrate with
2/5 + 7/4
Step 1:
Find the LCM of the denominators.
⇒ LCM of 5 & 4 = 20
Step 2:
In a turn by turn fashion, divide the found LCM from Step 1
by each denominator, multiplying the quotient by the corresponding numerator.
⇒
((2 x 4) + (7 x 5))/20
= (8 + 35)/20
Step 3:
Go ahead and add the numerators.
⇒
43/20
Create a new module file;
Call it AddFraction.pm.;
Type out the adjoining Perl code for adding fractions.
Note: The code module for
finding LCM
is from the Primary Category.
Just make a copy of it into the current folder (project).
You can comment out the DivideFraction Perl object
code in the main class from the previous lesson or simply continue from where it stopped.
So!
Feel free to try out your own set of numerators and denominators for fractional addition.
Perl code for AddFraction Module File
package ADDFRACTION;
BEGIN {
require Exporter;
our $VERSION = 2016.12;
our @ISA = qw(Exporter);
our @EXPORT_OK = qw(doAdd canoniseFraction);
}
use warnings;
use strict;
my $answer;
my (@numerators, @denominators, @new_numerators);
my %fractions;
sub new {
no warnings "all";
my $this = shift;
my $parameters = shift;
bless $parameters, $this;
$this->_init($parameters);
return $this;
}
sub _init {
my $self = shift;
my $aux = shift;
$fractions{numerators} = $aux->{numerators};
$fractions{denominators} = $aux->{denominators};
@numerators = @{$fractions{numerators}};
@denominators = @{$fractions{denominators}};
$answer = 0;
}
sub canoniseFraction {
my @new_nums;
use LCM;
my $lcm = LCM->new(\@denominators);
$lcm = $lcm->getLCM();
for (0 .. $
push @new_nums, ($lcm / $denominators[$_] * $numerators[$_]);
}
return (\@new_nums, $lcm);
}
sub doAdd {
my @help = canoniseFraction();
@new_numerators = @{$help[0]};
$answer += $new_numerators[$_] for 0 .. $
return ($answer, $help[1]);
}
1;
Main class
use strict;
use warnings;
use ADDFRACTION "doAdd";
my (@numerators, @denominators, @solutions);
my %fractions;
@numerators = (1, 1, 1, 1);
@denominators = (4, 4, 4, 4);
%fractions = (
numerators => \@numerators,
denominators => \@denominators
);
print "\n Solving:\n";
printf("%13u", $_) for @numerators;
printf("\n%12s", " ");
print "- + " for 1 .. $
printf("%2s\n", "-");
printf("%13u", $_) for @denominators;
print "\n";
my $add_fract = ADDFRACTION->new(\%fractions);
@solutions = $add_fract->doAdd();
printf("\n%25u\n", $solutions[0]);
printf("%25s\n", "Answer = -");
printf("%25u\n", $solutions[1]);
print "\n\n";