Fraction calculation in Perl

This Perl script is able to add,subtract,divide and multiply fractional numbers:

use strict;
#test data:
my @B1 = _read();
my @B2 = _read();
#test addition
my @BC = _add(@B1,@B2);
print "+:",_print(@BC);
# test substract
   @BC = _sub(@BC,@B2);
print "-:",_print(@BC);
#simplify the result
   @BC = simplify(@BC);

#test multiplication
   @BC = _mul(@B1,@B2);
print "*:",_print(@BC);
#test division
   @BC = _div(@BC,@B2);
print "/:",_print(@BC);
#simplify the result
   @BC = simplify(@BC);

sub _add {
    my $gn = $_[1]*$_[3];
    return(($_[0]*($gn/$_[1]))+($_[2]*($gn/$_[3])),$gn);
}

sub _sub {
    my $gn = $_[1]*$_[3];
    return(($_[0]*($gn/$_[1]))-($_[2]*($gn/$_[3])),$gn);
}

sub _mul {
    return($_[0]*$_[2],$_[1]*$_[3]);
}

sub _div {
    return($_[0]*$_[3],$_[1]*$_[2]);
}

sub _print {
    my @D = &simplify;
    my $c = 0;
    while(1){
        if($D[0]>=$D[1]){
            $D[0] -= $D[1];
            ++$c;
        }else{
            last;    
        }
    }
    if($c){
        return "$c+$D[0]/$D[1](".&fractial2number.")\n"; 
    }else{
        return "$D[0]/$D[1](".&fractial2number.")\n"; 
    }
}

sub _read {
    print "fractal number:";
    my $in = <STDIN>;
    if($in =~ /\//o){
       $in =~ /^(.+)\/(.+)$/o;
        return($1,$2);
    }else{
       return(number2fractial($in)); 
    }
}

sub number2fractial {
    $_[0] =~ /^(.+)\.(.+)$/o;
    my $d = $1;
    my $c = $2;
    my $u = $2;
       $u =~ s/./0/g;
       $u = "1".$u;
    return($c+($d*$u),"$u");
}

sub fractial2number {
    return($_[0]/$_[1]);
}

sub simplify {
    for($_ = $_[1];$_>=2;--$_){
        return($_[0]/$_,$_[1]/$_) if($_[0]%$_==0 && $_[1]%$_==0);
    }
    return($_[0],$_[1]);
}

This is the output from 1/2 and 1.25, at first add both then subtract from the result, multiply and then divide from the result:

fractal number:1/2  
fractal number:1.25 
+:1+3/4(1.75)       
-:1/2(0.5)          
*:5/8(0.625)        
/:1/2(0.5)

For a better result take a look at Perl high precision.

One thought on “Fraction calculation in Perl”

  1. Hi there, just became alert to your blog through
    Google, and discovered that it can be truly informative.
    I’m gonna be aware of brussels. I’ll appreciate should
    you continue this in future. A great deal of people will be benefited from your writing.
    Cheers!

Leave a Reply

Your email address will not be published.

fifteen + six =