Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

DecToFrac - Converts a decimal number into a fraction
[ All Languages » VB »  Math]

Total Hit ( 1733)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


Click here to copy the following block
' Converts a decimal value into fractional parts as integers
' (based on the concept of Continued Fractions)

' Examples of usage:

' Call DeclToFrac(0.125, a, b)  ' 1 and 8 are returned in a & b
' Call DecToFrac(5/40, a, b)   ' 1 and 8 are also returned
' Call DecToFrac(2/3, a, b)   ' 2 and 3 are returned



' Since more than one value needs to be returned, they are returned
' to variables which are passed by reference as arguments (Numerator
' and Denom) to the DecToFrac Sub procedure

Sub DecToFrac(DecimalNum As Double, Numerator As Long, Denom As Long)

  ' The BigNumber constant can be adjusted to handle larger fractional parts
  Const BigNumber = 50000
  Const SmallNumber = 1E-16

  Dim Inverse As Double, FractionalPart As Double
  Dim WholePart As Long, SwapTemp As Long

  Inverse = 1 / DecimalNum
  WholePart = Int(Inverse)
  FractionalPart = Frac(Inverse)

  If 1 / (FractionalPart + SmallNumber) < BigNumber Then
    ' Notice that DecToFrac is called recursively. 
    Call DecToFrac(FractionalPart, Numerator, Denom)
    Numerator = Denom * WholePart + Numerator

    SwapTemp = Numerator
    Numerator = Denom
    Denom = SwapTemp
  Else ' If 1 / (FractionalPart + SmallNumber) > BigNumber
    ' Recursion stops when the final value of FractionalPart is 0 or
    ' close enough. SmallNumber is added to prevent division by 0.
    Numerator = 1
    Denom = Int(Inverse)
  End If
End Sub

' This function is used by DecToFrac and DecToProperFact

Function Frac(x As Double) As Double
  Frac = Abs(Abs(x) - Int(Abs(x)))
End Function

' This additional procedure handles "improper" fractions and returns
' them in mixed form (a b/c) when the numerator is larger than the denominator

Sub DecToProperFrac(x As Double, a As Long, b As Long, c As Long)
  If x > 1 Then a = Int(x)
  If Frac(x) <> 0 Then
   Call DecToFrac(Frac(x), b, c)
  End If
End Sub


Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.