Nova Posted January 15, 2005 Share Posted January 15, 2005 Anyone know a way to return a fraction in its lowest form ? Example 8/10 would be equal to 4/5 I need it for a ratio calculation im trying to do. Link to comment Share on other sites More sharing options...
CyberSlug Posted January 15, 2005 Share Posted January 15, 2005 Off the top of my head (so it's not fully tested): $frac = Reduce(8, 10) Msgbox(4096,"Result", $frac[0] & "/" & $frac[1]) ;*** I'll assume that $numerator > $denominator *** Func Reduce($numerator, $denominator) Local $result[2] Local $t = $numerator While $t > 1 If IsInt($numerator/$t) And IsInt($denominator/$t) Then $numerator = $numerator / $t $denominator = $denominator / $t $t = $numerator Else $t = $t - 1 EndIf WEnd $result[0] = $numerator $result[1] = $denominator Return $result EndFunc Use Mozilla | Take a look at My Disorganized AutoIt stuff | Very very old: AutoBuilder 11 Jan 2005 prototype I need to update my sig! Link to comment Share on other sites More sharing options...
ezzetabi Posted January 15, 2005 Share Posted January 15, 2005 (edited) Assume nothing, works. Array[0] Denominator Array[1] Numerator expandcollapse popupLocal $frac[2] $frac[1] = -2 $frac[0] = -4 MsgBox(0,'',$frac[1] & '/' & $frac[0] & ' before') $frac = LowestForm($frac) MsgBox(0,'',$frac[1] & '/' & $frac[0] & ' after') $frac[1] = 6 $frac[0] = -4 MsgBox(0,'',$frac[1] & '/' & $frac[0] & ' before') $frac = LowestForm($frac) MsgBox(0,'',$frac[1] & '/' & $frac[0] & ' after') $frac[1] = 21 $frac[0] = -4999;4999 is prime. MsgBox(0,'',$frac[1] & '/' & $frac[0] & ' before') $frac = LowestForm($frac) MsgBox(0,'',$frac[1] & '/' & $frac[0] & ' after') Func LowestForm($aFrac) If Not IsArray($aFrac) Then Return '' If Not IsInt($aFrac[0]) Or Not IsInt($aFrac[1]) Then Return '' Local $c, $min, $neg = 0 If ($aFrac[0] * $aFrac[1]) < 0 Then $neg = 1 If ($aFrac[0] < 0) Then $aFrac[0] = $aFrac[0] * -1 If ($aFrac[1] < 0) Then $aFrac[1] = $aFrac[1] * -1 If $aFrac[0] < $aFrac[1] Then $min = $aFrac[0] Else $min = $aFrac[1] EndIf For $c = $min to 1 Step -1 If Mod($aFrac[0],$c)=0 And Mod($aFrac[1],$c)=0 Then $aFrac[0] = $aFrac[0] / $c $aFrac[1] = $aFrac[1] / $c ExitLoop EndIf Next If $neg = 1 Then $aFrac[1] = $aFrac[1] * -1 Return $aFrac EndFunc Edited January 15, 2005 by ezzetabi Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now