Created
October 7, 2014 14:07
-
-
Save dsparks/f287fa1494c57f49d7a9 to your computer and use it in GitHub Desktop.
Approximate any decimal with a rational fraction
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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