R function to try to find a fraction

Suppose you have a decimal value like 0.4171 that is an exact or approximate representation of a fraction. Below is an R function I wrote that tries to determine which fractions could have produced that value.

Here’s an example run:

> FindTheFraction(0.4171)
First 5 matching fractions with denominator under 1000
73/175=0.4171429
78/187=0.4171123
83/199=0.4170854
88/211=0.4170616
146/350=0.4171429

Here’s the function itself:

FindTheFraction <- function(x,maxhits=5,maxdenom=1000) {
  cat("First",maxhits,"matching fractions with denominator under",maxdenom,"\n")
  hits <- 0
  X <- x
  factor <- 1
  while ((X-trunc(X))>0)  { factor <- factor*10; X <- factor*x }
 
  denom <-2
  while ((denom<maxdenom) & hits<maxhits) {
    count <- 1:denom
    frac <- count/denom
    diff <- frac - x
    match <- abs(factor*diff)<0.5
    if (any(match)) {
      cat(count[match],"/",denom,"=",count[match]/denom,"\n",sep="")
      hits <- hits+1
    }
    denom <- denom+1
  }
}
Advertisements