如何将浮点数转换为由字节分子和分母表示的最接近的分数?

Eri*_*ric 5 java algorithm math floating-point fractions

如何编写一个算法,给定一个浮点数,并尝试使用分子和分母(两者都限制在 Java 字节的范围内)尽可能准确地表示?

原因是 I2C 设备需要分子和分母,而给它一个浮点数是有意义的。

例如,3.1415926535...将导致245/78, 而不是314/10022/7

就效率而言,在程序开始时会调用大约三次,但之后就不再调用了。所以慢的算法也不算糟糕。

Eri*_*ric 6

这是我最终使用的代码(基于uckelman的代码)

public static int[] GetFraction(double input)
{
    int p0 = 1;
    int q0 = 0;
    int p1 = (int) Math.floor(input);
    int q1 = 1;
    int p2;
    int q2;

    double r = input - p1;
    double next_cf;
    while(true)
    {
        r = 1.0 / r;
        next_cf = Math.floor(r);
        p2 = (int) (next_cf * p1 + p0);
        q2 = (int) (next_cf * q1 + q0);

        // Limit the numerator and denominator to be 256 or less
        if(p2 > 256 || q2 > 256)
            break;

        // remember the last two fractions
        p0 = p1;
        p1 = p2;
        q0 = q1;
        q1 = q2;

        r -= next_cf;
    }

    input = (double) p1 / q1;
    // hard upper and lower bounds for ratio
    if(input > 256.0)
    {
        p1 = 256;
        q1 = 1;
    }
    else if(input < 1.0 / 256.0)
    {
        p1 = 1;
        q1 = 256;
    }
    return new int[] {p1, q1};
}
Run Code Online (Sandbox Code Playgroud)

感谢那些帮助过的人


uck*_*man 4

我已经编写了一些代码(甚至是 Java 代码)来完成您所要求的操作。就我而言,我需要将缩放因子显示为百分比和比率。最熟悉的示例是您在图像编辑器(例如 GIMP)中看到的缩放对话框。

您可以在此处找到我的代码,位于从第 1161 行开始的 updateRatio() 方法中。只要 LGPL 许可证适用,您就可以简单地使用它。我所做的基本上遵循 GIMP 中所做的事情——这是几乎只有一种有效、合理的方法来完成的事情之一。