[R] Number -> Fraction
Thomas Lumley
tlumley at u.washington.edu
Thu Sep 13 17:34:24 CEST 2007
On Thu, 13 Sep 2007, Mauro Arnoldi wrote:
> Hi everybody!
> I'm new to this list and also to the R program.
>
> I'd like to know if there is a function able to convert results into
> Fractional form like my scientific calculator have. For example:
>
>> 1/3
> [1] 0.3333333
>
>> function_that_return_a_fraction_from_numbers(0.3333333)
> [1] 1/3
>
This must have some restrictions (so it doesn't return 3333333/1000000,
which would be a more accurate fraction).
One approach is
> unfrac <- function(x, max=100, tol=0.01){
num <- x * (1:max)
err <- (num - round(num)) * (1:max)
if (!any(abs(err) < tol))
return(NA)
i <- which.min(abs(err))
c(round(num[i]), i)
}
This returns the best fraction approximation with denominator up to `max`,
where `best` is in terms of the non-integer part of the numerator, and no
answer is given if the non-integer part of the numerator is more than
`tol`
> unfrac(0.3333333)
[1] 1 3
> unfrac(pi)
[1] NA
> unfrac(pi,max=1000)
[1] 355 113
> unfrac(pi,tol=0.1)
[1] 22 7
-thomas
More information about the R-help
mailing list