Re: Fraction Maker
Re: Fraction Maker
- Subject: Re: Fraction Maker
- From: Graff <email@hidden>
- Date: Wed, 20 Oct 2004 21:29:10 -0400
Here's a handler that I just whipped up which does this:
----
on DecimalToFraction(theNumber, maxSteps)
-- recursive algorithm
-- uses Method of Continued Fractions
set numerator to missing value
set denominator to missing value
set sign to 1
set numClass to class of theNumber
if ((numClass is real) or (numClass is integer)) then
if (theNumber < 0) then
set sign to -1
set theNumber to theNumber * -1
end if
set invert to 1 / theNumber
if (maxSteps > 0) then
set wholePart to round invert rounding down
set decimalPart to invert - wholePart
if (decimalPart > 1.0E-3) then
set returnValue to DecimalToFraction(decimalPart, maxSteps - 1)
set numerator to (item 2 of returnValue) * sign
set denominator to wholePart * (item 2 of returnValue) + (item
1 of returnValue)
else
set denominator to wholePart * sign
set numerator to 1
end if
else
set numerator to (round invert rounding to nearest) * sign
set denominator to 1
end if
end if
return {numerator, denominator}
end DecimalToFraction
set testNum to 0.12321
set {numerator, denominator} to DecimalToFraction(testNum, 10)
display dialog "" & testNum & " is approximately " & numerator & "/" &
denominator
--> a dialog box that says "0.12321 is approximately 6367/51676"
----
You call it with the number to convert and a "maxSteps" number
representing how accurate you want the answer. The "maxSteps" number
just tells the handler how many times to iterate. This is so that
irrational numbers, like PI, won't cause it to just sit there and work
forever.
With a bit of testing I found that a value of 10 for maxSteps is plenty
for most numbers.
- Ken
On Oct 20, 2004, at 9:44 AM, Jason Bourque wrote:
Does anyone have a Fraction Maker?
I have the larger value 1 and a smaller decimal .66
And I want to get 2/3. I now it will take some rounding.
I appreciate the help.
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Applescript-users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden