/** * Utility class for getting fractions from decimals as an array of values or a string * * @author Phil Douglas * @version 1.0 * * website : http://www.lookmumimontheinternet.com * email : phil@lookmumimontheinternet.com * * based on information from: * * http://proto.layer51.com/d.aspx?f=289 * http://ericlin2.tripod.com/mis/ration.html * */ class com.lookmum.util.Fraction { // class variable, limits the amount of iterations in finding the fraction to prevent infinite loops public static var iterationLimit : Number = 10000 private static var it : Number = 0 // class variable, the accuracy to which to find the fraction (used for infinately recurring decimals e.g. 1/3) public static var accuracy : Number = 0.00001 private function Fraction () { //class is static utility class so no need to instantiate } private static function resetIt () : Void { it = 0 } private static function addIt () : Boolean { it ++ if (it == iterationLimit) { trace ('error : too many iterations') return true } } /** * Static class method, returns a fraction from a decimal as a string * * @usage com.lookmum.util.Fraction.getFractionString(0.5) // returns "1/2" * com.lookmum.util.Fraction.getFractionString(1.5) // returns "1 1/2" * com.lookmum.util.Fraction.getFractionString(1) // returns "1" * * @param num the decimal to find the corresponding fraction for * * @return a string of the fraction * */ public static function getFractionString (num : Number) : String { var fracString : String var fracArray : Array = getFraction (num) switch (fracArray.length) { case 1 : fracString = num.toString () break case 2 : fracString = fracArray [0].toString () + '/' + fracArray [1].toString () break case 3 : fracString = fracArray [0].toString () + ' ' + fracArray [1].toString () + '/' + fracArray [2].toString () break } return fracString } /** * Static class method, returns a fraction from a decimal as an array * * @usage com.lookmum.util.Fraction.getFraction(0.5) // returns [1,2] * com.lookmum.util.Fraction.getFraction(1.5) // returns [1,1,2] * com.lookmum.util.Fraction.getFraction(1) // returns [1] * * @param num the decimal to find the corresponding fraction for * * @return an array of the fraction of length 1-3 * */ public static function getFraction (num : Number) : Array { var fracArray : Array = new Array () var hasWhole : Boolean = false if (num >= 1) { hasWhole = true fracArray.push (Math.floor (num)) } if (num - Math.floor (num) == 0) { return fracArray } if (hasWhole) { num = num - Math.floor (num) } var a : Number = num - int (num); var p : Number = 0; var q : Number = a; resetIt () while (Math.abs (q - Math.round (q)) > accuracy) { addIt () p ++; q = p / a; } fracArray.push (Math.round (q * num)) fracArray.push (Math.round (q)) return fracArray } }