IT Help Desk > Web based Developer Forum

Basic Operatins with Fractions (PHP code)

(1/1)

msu_math:
The following function FracOper($A, $Oper, $B) returns the sum $A+$B, difference $A-$B, product $A*$B and quotient $A/$B of the fractions $A & $B according the operations ($Oper) "+", "-", "*" and "/" respectively. 

function FracOper($A, $Oper, $B)

 {
   $C=NumLCM(FracDenom($A), FracDenom($B));

   if($Oper=="+")
          return FracSymp(($C/FracDenom($A))*FracNumer($A)+($C/FracDenom($B))*FracNumer($B)."/".$C);

   elseif($Oper=="-")
          return FracSymp(($C/FracDenom($A))*FracNumer($A)-($C/FracDenom($B))*FracNumer($B)."/".$C);

   elseif($Oper=="*")
          return FracSymp(FracNumer($A)*FracNumer($B)."/".FracDenom($A)*FracDenom($B));

   elseif($Oper=="/")
          return FracSymp(FracNumer($A)*FracDenom($B)."/".FracDenom($A)*FracNumer($B));

   else { echo "Undefined Operation !";  return NULL; }
 }

msu_math:
The FracOper() function can be subdivided into four distinct functions:

  function FracSum($A, $B)

    {
         return FracSymp(($C/FracDenom($A))*FracNumer($A)+($C/FracDenom($B))*FracNumer($B)."/".$C);
    }


   function FracDifference($A, $B)

    {
         return FracSymp(($C/FracDenom($A))*FracNumer($A)-($C/FracDenom($B))*FracNumer($B)."/".$C);
    }


   function FracProduct($A, $B)

    {
         return FracSymp(FracNumer($A)*FracNumer($B)."/".FracDenom($A)*FracDenom($B));
    }


   function FracQuotient($A, $B)

    {
         return FracSymp(FracNumer($A)*FracDenom($B)."/".FracDenom($A)*FracNumer($B));
    }

msu_math:
Sample Return Values:

1.  FracSum("2/3", "1/4")  returns  "11/12"

2. FracDifference("2/3", "1/4")  returns  "5/12"

3. FracProduct("2/3", "1/4")  returns  "1/6" 

4. FracQuotient("2/3", "1/4")  returns  "8/3"

Navigation

[0] Message Index

Go to full version