For many people the mere mention of fractions elicits a wince, and while these lovely math constructs played a notable role in our early years of math, they are reasonably simple entities. While most humans revisit fractions over many years and often still fail to grasp the concept, for a computer, the elementary operations with fractions (addition, subtraction, multiplication, division, and the necessary greatest common factor (GCF) and lowest common multiple (LCM)) can be coded in just a few lines.
While by no means a perfect class (quite possibly a rather poorly coded class), the following provides some basic functions necessary for working with fractions.
n = $num;
$this->d = $den;
}
public function gcf($n1, $n2){
if ($n2>$n1){
$tmp = $n1;
$n1=$n2;
$n2=$tmp;
}
do{
$rem = $n1 % $n2;
$n1 = $n2;
$n2 = $rem;
}while($rem!=0);
return $n1;
}
public function lcm($n1, $n2){
return $n1*($n2/frac::gcf($n1,$n2));
}
public function reduce (){
$g = $this->gcf($this->n,$this->d);
$this->n /= $g;
$this->d /= $g;
}
public function multiply (frac $n1, frac $n2){
$f = new frac($n1->n*$n2->n,$n1->d*$n2->d);
$f->reduce();
return $f;
}
public function divide (frac $n1, frac $n2){
return frac::multiply($n1, new frac($n2->d,$n2->n));
}
public function add (frac $n1, frac $n2){
$g = frac::lcm($n1->d,$n2->d);
$f= new frac($n1->n*($g/$n1->d)+$n2->n*($g/$n2->d),$g);
$f->reduce();
return $f;
}
public function subtract (frac $n1, frac $n2){
return frac::add($n1, new frac(-1*$n2->n,$n2->d));
}
public function display(){
return $this->n . "/" . $this->d;
}
}
?>
Examples of use:
1/3 + 1/2:
display();
?>
1/8 * 2/5
display();
?>
The gcf
function uses Euclid’s algorithm, and the lcm
function (used to find the common denominator) calls the gcf
function.
Given the significant disparity between the ease with which a computer can ‘learn’ fractions, and the difficulty encountered by most students, perhaps it is time to consider teaching fractions as a series of concrete steps – an algorithm – instead of the current method. (Granted, most current methods do provide a method for arriving at an answer, but especially for the determination of the lowest common denominator (or reducing fractions), a procedural methodology (e.g. prime factoring, Euclid’s method, etc) is rarely given.)