algorithm - 如何将 float 转换为人类可读的分数?

标签 algorithm language-agnostic numbers

假设我们有0.33,我们需要输出1/3
如果我们有 0.4,我们需要输出 2/5

我们的想法是让它变得易于阅读,让用户理解“y 中的 x 部分”作为理解数据的更好方式。

我知道百分比是一个很好的替代方法,但我想知道是否有一种简单的方法可以做到这一点?

最佳答案

我找到了 David Eppstein 的 find rational approximation to given real number C 代码正是您所要求的。它基于连分数理论,非常快速且相当紧凑。

我使用了针对特定分子和分母限制定制的版本。

/*
** find rational approximation to given real number
** David Eppstein / UC Irvine / 8 Aug 1993
**
** With corrections from Arno Formella, May 2008
**
** usage: a.out r d
**   r is real number to approx
**   d is the maximum denominator allowed
**
** based on the theory of continued fractions
** if x = a1 + 1/(a2 + 1/(a3 + 1/(a4 + ...)))
** then best approximation is found by truncating this series
** (with some adjustments in the last term).
**
** Note the fraction can be recovered as the first column of the matrix
**  ( a1 1 ) ( a2 1 ) ( a3 1 ) ...
**  ( 1  0 ) ( 1  0 ) ( 1  0 )
** Instead of keeping the sequence of continued fraction terms,
** we just keep the last partial product of these matrices.
*/

#include <stdio.h>

main(ac, av)
int ac;
char ** av;
{
    double atof();
    int atoi();
    void exit();

    long m[2][2];
    double x, startx;
    long maxden;
    long ai;

    /* read command line arguments */
    if (ac != 3) {
        fprintf(stderr, "usage: %s r d\n",av[0]);  // AF: argument missing
        exit(1);
    }
    startx = x = atof(av[1]);
    maxden = atoi(av[2]);

    /* initialize matrix */
    m[0][0] = m[1][1] = 1;
    m[0][1] = m[1][0] = 0;

    /* loop finding terms until denom gets too big */
    while (m[1][0] *  ( ai = (long)x ) + m[1][1] <= maxden) {
        long t;
        t = m[0][0] * ai + m[0][1];
        m[0][1] = m[0][0];
        m[0][0] = t;
        t = m[1][0] * ai + m[1][1];
        m[1][1] = m[1][0];
        m[1][0] = t;
        if(x==(double)ai) break;     // AF: division by zero
        x = 1/(x - (double) ai);
        if(x>(double)0x7FFFFFFF) break;  // AF: representation failure
    } 

    /* now remaining x is between 0 and 1/ai */
    /* approx as either 0 or 1/m where m is max that will fit in maxden */
    /* first try zero */
    printf("%ld/%ld, error = %e\n", m[0][0], m[1][0],
           startx - ((double) m[0][0] / (double) m[1][0]));

    /* now try other possibility */
    ai = (maxden - m[1][1]) / m[1][0];
    m[0][0] = m[0][0] * ai + m[0][1];
    m[1][0] = m[1][0] * ai + m[1][1];
    printf("%ld/%ld, error = %e\n", m[0][0], m[1][0],
           startx - ((double) m[0][0] / (double) m[1][0]));
}

关于algorithm - 如何将 float 转换为人类可读的分数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/95727/

相关文章:

c# - 我们可以改进这个 o(mn) 的 bin 计数算法吗?

java - 从给定范围内的数组中查找峰值

algorithm - 检测有向依赖图中的循环并检测顶点是循环的一部分还是仅依赖于一个顶点

google-analytics - Google Analytics 行为流数据导出?

algorithm - 使用递归检查数组元素是否是两个较早元素的总和

debugging - 什么是调试器以及它如何帮助我诊断问题?

java - 创建方法过滤器

regex - 如何从R中的字符串中仅删除 "actual numbers"

algorithm - 从集合中以相等概率选择数字

java - 查找子列表的索引