Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.