# Fraction calculation in Perl

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

```use strict;
#test data:
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);

my \$gn = \$_*\$_;
return((\$_*(\$gn/\$_))+(\$_*(\$gn/\$_)),\$gn);
}

sub _sub {
my \$gn = \$_*\$_;
return((\$_*(\$gn/\$_))-(\$_*(\$gn/\$_)),\$gn);
}

sub _mul {
return(\$_*\$_,\$_*\$_);
}

sub _div {
return(\$_*\$_,\$_*\$_);
}

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

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

sub number2fractial {
\$_ =~ /^(.+)\.(.+)\$/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(\$_/\$_);
}

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

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. KingODibrell says: