将任何比例四舍五入到最接近的1 / r形式的算法

Ser*_*ues 6 r fractions

在计算比例(0 <x <1)时,我希望将结果x转换为最接近的1 / r形式,例如

x = 0.30转换为1/3

而对于

x = 0.29转换为1/4

我一直在尝试使用来自MASS的round()和fractions()的不同想法,但收效甚微。

您可能会用R中最简单的解决方案来解决这个问题?

Bil*_*ien 2

findR <- function(x){
    possibles <- 1/seq(1:100)
    diffs <- abs(x - possibles)
    1/possibles[which.min(diffs)]}


df <- data.frame(x = seq(.1, .3, .01))
df$r <- sapply(df$x, findR)

      x  r
1  0.10 10
2  0.11  9
3  0.12  8
4  0.13  8
5  0.14  7
6  0.15  7
7  0.16  6
8  0.17  6
9  0.18  6
10 0.19  5
11 0.20  5
12 0.21  5
13 0.22  5
14 0.23  4
15 0.24  4
16 0.25  4
17 0.26  4
18 0.27  4
19 0.28  4
20 0.29  4
21 0.30  3
Run Code Online (Sandbox Code Playgroud)