Skip to content

Instantly share code, notes, and snippets.

@dsparks
Created October 7, 2014 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsparks/f287fa1494c57f49d7a9 to your computer and use it in GitHub Desktop.
Save dsparks/f287fa1494c57f49d7a9 to your computer and use it in GitHub Desktop.
Approximate any decimal with a rational fraction
rationalFractionApproximator <- function(dec, maxDenom = 1000){
denomSeq <- 1:maxDenom
impliedNumerator <- dec * denomSeq
roundNumerator <- round(impliedNumerator)
absError <- abs(roundNumerator / denomSeq - dec)
minMinimand <- which.min(absError * denomSeq)
minDenom <- denomSeq[minMinimand]
minNumer <- roundNumerator[minMinimand]
line2 <- paste0(minNumer, " / ", minDenom, " = ", minNumer / minDenom)
tempLen <- nchar(paste0(minNumer, " / ", minDenom, " = "))
line1 <- paste0("match:", paste0(rep(" ", tempLen-6), collapse = ""), dec)
print(line1)
print(line2)
out <- list()
out$Numer <- minNumer
out$Denom <- minDenom
return(out)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment