| |||||||||||||||||
![]() |
![]() |
![]() |
|||||||||||||||
|
Decimal to Fraction Conversion How do we obtain approximation ratio of a real number? Suppose you have a number with several decimal digits like this: 2.14567, what is the best rational approximation of this number? What is the error of this approximation? Of course, we can always say that 2.14567 = 214567/100000 without any approximation. However, some number like
Algorithm: Suppose we have a decimal number At the beginning, we compute term, error and reciprocal of remainder respectively as
Then continued the iteration with iteration formula
Once we get the term of continued fraction, we can use the difference equation
The iteration is stop when the absolute error is very small
Example (hand calculation):
We start with making a continued fraction. We use difference equation with initial condition
The first iteration we have
The second iteration we have
The third iteration we have
Visual Basic code for this conversion is given below
Function Decimal2Fraction(ByVal decNum As Double, ByVal accuracy As Double, _ ByRef nominator, ByRef denominator, ByRef remainder) ' Input decNum always between zero to 1 ' copyright (c) Kardi Teknomo 2006 ' http://people.revoledu.com/kardi Dim a(25) ' I assume the accuracy is lower than 25 digit decimalsDim y(25), r(25)Dim p(25), q(25)Dim errorDim i As Integer, k As IntegerDim ratio As Double, prevRatio As DoubleFor k = 0 To 24If k = 0 Thena(0) = Int(decNum) ' function Int in VB is equivalent to Floorr(0) = decNum - a(0)If r(0) <> 0 Then y(0) = 1 / r(0)p(0) = a(0)q(0) = 1ratio = p(0) / q(0)error = Abs(decNum - ratio)Elsea(k) = Int(y(k - 1)) ' function Int in VB is equivalent to Floorr(k) = y(k - 1) - a(k)y(k) = 1 / r(k)If k = 1 Thenp(1) = a(1) * p(0) + 1q(1) = a(1) * q(0)Elsep(k) = a(k) * p(k - 1) + p(k - 2)q(k) = a(k) * q(k - 1) + q(k - 2)End Ifratio = p(k) / q(k)error = Abs(ratio - prevRatio)End IfIf error < accuracy ThenExit ForElseprevRatio = ratioEnd IfNext k' report the resultsnominator = p(k - 1)denominator = q(k - 1)remainder = r(k - 1)Decimal2Fraction = nominator / denominatorEnd Function Try the online interactive program that use the above Decimal to Fraction code so that you can see the code in action. Alternatively, you may use the program or spreadsheet companion of this tutorial to get conversion of any decimal numbers. For example, try interesting number such as Preferable reference for this tutorial is Teknomo, Kardi. Continued Fraction. http://people.revoledu.com/kardi/tutorial/ContinuedFraction/index.html
|
|||||||||||||||
|
||||||||||||||||
© 2006 Kardi Teknomo. All Rights Reserved. Designed by CNV Media |
||||||||||||||||