This Perl script is able to add,subtract,divide and multiply fractional numbers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
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:
1 2 3 4 5 6 |
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.
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!