Fraction AlgorithmDate: 03/19/2002 at 08:20:50 From: Gil Barak Subject: Fraction Algorithm I read one of the posts about how to find finite decimals such as .078349 and convert them into fractions. I have been having trouble making an application that can convert the decimal into a fraction without doing 78349/1000000. Could you please give me the algorithm for this operation, in either Pascal or Visual Basic? Thanks, Gil Date: 03/19/2002 at 12:08:50 From: Doctor Peterson Subject: Re: Fraction Algorithm Hi, Gil. I presume this is the page you read: Decimal To Fraction Conversion http://mathforum.org/dr.math/problems/lawson6.25.98.html You may be able to program more easily from the explanation in our FAQ on fractions (see section C, Fractions with Small Denominators): http://mathforum.org/dr.math/faq/faq.fractions.html#decfrac Here is a Visual Basic program that implements the algorithm on that page: Private Sub ConvertToFraction(ByVal V As Double, N As Long, D As Long) Const MaxTerms = 15 'Limit to prevent infinite loop Const MinDivisor = 0.000001 'Limit to prevent divide by zero Const MaxError = 0.00000001 'How close is enough Dim F As Double 'Fraction being converted Dim A As Long 'Current term in continued fraction Dim N1 As Long 'Numerator, denominator of last approx Dim D1 As Long Dim N2 As Long 'Numerator, denominator of previous approx Dim D2 As Long F = V 'Initialize fraction being converted N1 = 1 'Initialize fractions with 1/0, 0/1 D1 = 0 N2 = 0 D2 = 1 For i = 0 To MaxTerms A = Int(F) 'Get next term F = F - A 'Get new divisor N = N1 * A + N2 'Calculate new fraction D = D1 * A + D2 N2 = N1 'Save last two fractions D2 = D1 N1 = N D1 = D 'Quit if dividing by zero If F < MinDivisor Then Exit For 'The following line shows the data for the table found in 'http://mathforum.org/dr.math/faq/faq.fractions.html 'and should be removed for actual use MsgBox "n:" & i & vbCrLf & "Quotient:" & F + A & vbCrLf & _ "a(n):" & A & vbCrLf & "Fraction:" & F & vbCrLf & _ "Reciprocal:" & 1 / F & vbCrLf & _ "Value:" & N & "/" & D & "=" & N / D 'Quit if close enough If Abs(V - N / D) < MaxError Then Exit For F = 1 / F 'Take reciprocal Next i End Sub - Doctor Peterson The Math Forum http://mathforum.org/dr.math/ Date: 03/20/2002 at 16:24:02 From: Gil Barak Subject: Fraction Algorithm Thanks, this will help me a lot. |
Search the Dr. Math Library: |
[Privacy Policy] [Terms of Use]
Ask Dr. Math^{TM}
© 1994-2015 The Math Forum
http://mathforum.org/dr.math/